【问题标题】:Passing objects as parameters to ActionResult methods in ASP .Net MVC from desktop client从桌面客户端将对象作为参数传递给 ASP .Net MVC 中的 ActionResult 方法
【发布时间】:2009-04-03 14:26:17
【问题描述】:

给定以下代码:

using (var client = new WebClient())
  {
    string url = string.Concat(someUrl, "SomeControllerName/", currentId, "/WriteLogFile");
    var toWrite = DateTime.Now

    /* Code to post object to URL goes here e.g. client.UploadValues(url, someNameValueCollectionObject)*/
  }

以及控制器方法签名:

public ActionResult WriteLogFile(DateTime date, int id)

如何使代码的第一部分将 DateTime 对象传递给此 ActionResult 方法?

【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

    您可以使用格式字符串作为日期

    string url = string.Format("someUrl/SomeControllerName/WriteLogFile/{0}/{1}", currentId, DateTime.Now.ToString("MM-dd-yyyy"));
    

    并在路由表中添加一个条目以将其路由到适当的控制器和操作

    routes.MapRoute("SomeRoutename",
                    "SomeControllerName/WriteLogFile/{id}/{date}",
                    new {   controller = "SomeControllerName", action = "WriteLogFile", 
                            date= DateTime.Now});
    

    【讨论】:

      【解决方案2】:

      添加查询字符串参数:

      var toWrite = DateTime.Now;
      string url = string.Concat(someUrl, "SomeControllerName/", currentId, "/WriteLogFile");
      url = string.Concat(url, "?date=", toWrite.ToString("s"));
      

      【讨论】:

      • 这就是我目前拥有的解决方案。我将每个对象转换为其字符串表示形式。
      • 好吧,无论您必须转换为字符串表示形式,因为您正在发出 HTTP 请求。如果您没有包含“日期”参数的路由,则必须按照 Craig 的建议使用 QueryString。
      • 嗯,这是唯一的方法。 Http 是纯文本:blogs.teamb.com/craigstuntz/2009/02/16/38024 查询字符串是文本。表单域是文本。您可以在 GET 请求中传递给服务器的所有内容都是文本。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      相关资源
      最近更新 更多