【问题标题】:JSON to MVC Object from an Ajax Post从 Ajax Post 到 MVC 对象的 JSON
【发布时间】:2017-06-07 13:14:57
【问题描述】:

我有这个从表中获取值的 json 数组变量:

var data = { "Model": [] };
$(".student-grade-data-row").each(function () {
    data.Model.push({
        'subjectId' : currentSubjectId,
        'studentId': $(this).attr('id'),
        'grade1' : $(this).find(".grade-select").val(),
        'mult' : $(this).find(".mult-select").val(),
        'subject': $(this).find(".topic-input").val(),
    });
});

它被制作成类似于名为 grade 的 MVC 类

public partial class grade
{
    public int id { get; set; } //auto-set
    public int subjectId { get; set; }
    public string studentId { get; set; }
    public int grade1 { get; set; }
    public int mult { get; set; }
    public string subject { get; set; }
    public System.DateTime date { get; set; } //auto-set
}

现在在完美的世界中,我希望将 data 变量中的值发送到我的控制器,如下所示:

$.ajax({
    url: '/Ajax/SendGrades',
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    success: function (dt) {
        console.log(dt);
    }
});

然后我可以把它捡起来,并将它序列化为一个合适的对象列表。

问题是我什至看不到我真正发送给控制器的内容以及我怎么可能将它链接到对象。

我尝试让函数采用 List<grade> Model 类型的 agrument,但它会一直告诉我值为 null。


我尝试使用一些基本的序列化,但也无法正常工作。代码

public ActionResult SendGrades(JsonResult Model)
{
    List<grade> g = new List<grade>();
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(grade));
    g = (List<grade>)serializer.ReadObject(Model);
    return Content("Hi");
}

给我一​​个错误提示

无法从 System.Web.Mvc.JsonResult 转换为 System.IO.Stream

这样做的正确方法是什么,以便我以后可以安全地将值存储在我的数据库中?

我对这种类型的工作相当陌生,所以对于任何菜鸟主义,我深表歉意。 任何帮助在这里都会很棒。

【问题讨论】:

  • 将方法更改为public ActionResult SendGrades(List&lt;grade&gt; Model)(并始终使用url: 'Url.Action("SendGrades", "Ajax")', 生成正确的url)。您还需要设置contentType: "application/json; charset=utf-8",
  • 此方法在测试时声称返回空变量。如果我运行 return content(Model.First().subject) 我会得到一个 NULL 错误。我正在使用单独的 js 文件来发送值。这可以使用Url.Action吗?
  • 你看到编辑的评论了吗(关于设置contentType选项)?
  • 是的。我现在将编辑答案
  • 你不能在外部文件中使用剃须刀代码,但你可以将它传递给 js 文件,例如只需使用var url = '@Url.Action(..)'; 在主视图中创建一个全局变量,或者使用data-url="@Url.Action(..)" 在触发ajax 的元素中分配它

标签: c# json ajax asp.net-mvc asp.net-mvc-4


【解决方案1】:

你的 ajax 选项需要包含

type: 'POST'

默认情况下,它是一个没有正文的GET,因此设置contentType 是没有意义的,DefaultModelBinder 不会使用JsonValueProvider(对于GET,数据的格式将需要成为data: { [0]subjectId: value, [0]studentId: value, [1]subjectId: value, [0]studentId: value, ....etc } - 即索引属性名称)

完整的代码需要

$.ajax({
    url: '/Ajax/SendGrades',
    type: 'POST', // add this
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    success: function (dt) {
        console.log(dt);
    }
});

以及控制器方法

public ActionResult SendGrades(List<grade> model)

【讨论】:

    【解决方案2】:

    你可以试试这个。再添加一个包含成绩列表作为属性的类

    class Models
    {
        public List<grade> Model{get; set;}
    }
    

    并像这样更改您的方法

    public ActionResult SendGrades(Models models)
    {
        List<grade> g = models.Model;
        //then write your logic here
    }
    

    【讨论】:

    • SendGrades(List&lt;grade&gt; Model)方式相同的错误
    【解决方案3】:

    你的模型应该是这样的

    public partial class grade
    {
        public int id { get; set; } //auto-set
        public int subjectId { get; set; }
        public string studentId { get; set; }
        public int grade1 { get; set; }
        public int mult { get; set; }
        public string subject { get; set; }
        public System.DateTime date { get; set; } //auto-set
    }
    

    当您使用data.Model 将数据发送到服务器分配数据时,您正在将值设置为模型

    $.ajax({
        url: '/Ajax/SendGrades',
        type: "POST",
        data: data.Model, //try to change it in ur code first if not work use jquery.post
        contentType: "application/json; charset=utf-8",
        success: function (dt) {
        console.log(dt);
        }
    });
    

    或使用 Jquery Post

    $.post('/Ajax/SendGrades', data.Model,
           function(data){
            console.log(data);
           });
    

    在控制器中

    public ActionResult SendGrades(List<grade> Model)
    {
          //then write your logic here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 2022-06-14
      • 2015-05-23
      • 2016-05-01
      • 2015-05-03
      • 2018-07-19
      相关资源
      最近更新 更多