【问题标题】:How to Pass Complex Type to ASP.NET MVC Controller using Ajax and jQuery如何使用 Ajax 和 jQuery 将复杂类型传递给 ASP.NET MVC 控制器
【发布时间】:2016-02-09 22:19:21
【问题描述】:

我在另一个复杂类型 (Model) 中获取复杂变量 (RamarksList) 属性的空值。

查看 NameType 的正确值,但我看到复杂类型 RemarksList 的属性(参数和注释)的值为空强> .

这是我的代码。请看看并提出建议。

jQuery:

 var data = {               
            'Name': 'Apple',
            'Type': 'Fruit',
            'RemarksList': [
              {
                  'Parameter': 'test 1',
                  'Comments': 'test 123'
              },
              {
                  'Parameter': 'test 2',
                  'Comments': 'abc 3455'
              }
            ]
        };



var url = "/Controller/Action";

            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'application/json',
                data: data,
                success: function (data) {

                }
            });

控制器:

[HttpPost]
        public ActionResult Save(Model model)
        {
            return View();
        }

模型类:

public class Model
    {
        public int Id { get; set; }      
        public string Name { get; set; }
        public string Type{ get; set; }
        public List<Remarks> RemarksList { get; set; }
    }

public class Remarks
{
    public int Id { get; set; }
    public string Parameter { get; set; } 
    public string Comments { get; set; } 
}

【问题讨论】:

  • data: JSON.stringify(data),
  • 试过了。有了这个,我得到了所有的东西,包括类型和名称..不知道为什么..
  • 对不起,你还需要contentType: 'application/json; charset=utf-8'
  • 完美。谢谢你。它正在工作..我是否需要同时设置 dataType: 'application/json', contentType: 'application/json; charset=utf-8',?
  • contentType 用于发送给控制器的数据,dataType 用于服务器发送回客户端的数据

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


【解决方案1】:

我把你的代码放在我的测试项目中,我得到了正确的数据。实际上 RemarksList 不是 null 并且工作正常!!

Result.

【讨论】:

  • W/O 内容类型,RemarksList 计数为 2,但 Parameter 和 Comments 为 NULL。正如我在评论中提到的,添加 stringfy 和 ContentType 后,一切看起来都很好。
【解决方案2】:

首先使用 JSON.stringify 将数据转换成字符串

$.ajax({
                url: url,
                type: 'POST',
                dataType: 'application/json',
                data: JSON.stringify(data),
                success: function (data) {

                }
            });

然后从以下更改控制器代码

        [HttpPost]
        public ActionResult Save(string model)
        {
           JavaScriptSerializer json_serializer = new JavaScriptSerializer();
           Model routes_list =(Model)json_serializer.DeserializeObject(model);
           return View();
        }

【讨论】:

    猜你喜欢
    • 2010-09-21
    • 1970-01-01
    • 2020-11-22
    • 2018-09-10
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多