【问题标题】:To pass whole JSON objects into controller of MVC将整个 JSON 对象传递给 MVC 的控制器
【发布时间】:2012-01-16 13:20:51
【问题描述】:

我想将整个 JSON 对象传递给 MVC 中的控制器,以便我可以访问整个对象。 我正在使用以下代码..

在视图中调用的脚本

var Email = {
            To:  $("#txtTo").val(),
            Text:  $("#txtTest").val(),
            Subject: $("#txtSubject").val()
        };

        $.ajax({
            type: "POST",
            url: ("Controller/SendEmail"),
            data: JSON.stringify(Email ),
            datatype: "json",
            contentType: "application/json; charset=utf-8",
            cache: false,
            success: function(htmlResult) {
                alert("Mail Send")
            },
            error: function(msg) { alert("Error Occurs."); }
        });

但是当我在控制器中调用它时:

 public ActionResult SendEmail(Model model)
            {
                string to = model.To ;
    }

它给出空值。如何解决?

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    如果您只发送data: Email,而不是其字符串化表示,模型绑定器将能够将传递的参数绑定到操作输入参数。

    这样,数据将不会通过JSON.stringify 而是通过$.param 处理,这将为您提供这样的字符串:

    To=abc&Text=xyz&Subject=123
    

    这就是始终将参数发布到服务器的方式。因此,这相当于一次传递一个变量。如果这些参数的名称与输入参数对象中的属性名称匹配,则默认模型绑定器将尝试使用发布的数据填充该对象。

    【讨论】:

      【解决方案2】:

      你必须像这样创建一个类:

      public class ObjectFilter : ActionFilterAttribute
              {
                  public string Param { get; set; }
                  public Type RootType { get; set; }
      
                  public override void OnActionExecuting(ActionExecutingContext filterContext)
                  {
                      if ((filterContext.HttpContext.Request.ContentType ?? string.Empty).Contains("application/json"))
                      {
                          object o = new System.Runtime.Serialization.Json.DataContractJsonSerializer(RootType).ReadObject(filterContext.HttpContext.Request.InputStream);
                          filterContext.ActionParameters[Param] = o;
                      }
                  }
              }
      

      您想要传递给 JSON 的类如下:

      public class Email
              {
                  public To{ get; set; }
                  public string Subject { get; set; }
                  public string Text { get; set; }
              }
      

      现在必须在你的控制器中调用这个类作为属性:

      [ObjectFilter(Param = "model", RootType = typeof(Email))]
      public ActionResult SendEmail(Email model)
                  {
                      string to = model.To ;
          }
      

      这会给你想要的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-05
        • 1970-01-01
        • 1970-01-01
        • 2017-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多