使用 .ajax 发布到 MVC 4 控制器时,ViewModel 始终为 null

本文关键字:ViewModel null 控制器 ajax MVC 使用 | 更新日期: 2023-09-27 18:36:40

My jQuery/HTML:

@using(Html.BeginForm("Create", "Home", FormMethod.Post)) {
    <input name="ImageName" id="ImageName" type="hidden" />
    <input name="XPos" id="XPos" type="hidden" />
    <input name="YPos" id="YPos" type="hidden" />
    <input name="Height" id="Height" type="hidden" />
    <input name="Width" id="Width" type="hidden" /> 
    <button id="submit" value="submit">Create it!</button>
}

$('form').submit(function () {
    var parameters = [];
    parameters.push({
        ImageName: $('#imagename').val(),
        XPos: $('#xpos').val(),
        YPos: $('#ypos').val(),
        Height: $('#height').val(),
        Width: $('#width').val()
    });
    console.log(JSON.stringify(parameters));
    $.ajax({
        url: '@Url.Action("Create", "Home")',
        type: 'Post',
        data: JSON.stringify(parameters),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            //yadda
        },
        error: function (xhr, status, error) {
          //yadda
        }
    });

这是我的观点模型:

public class Image{
    public string ImageName { get; set; }
    public double Xpos { get; set; }
    public double Ypos { get; set; }
    public double Height{ get; set; }
    public double Width { get; set; }
}

这是我的控制器。

这是 JSON.stringify(parameters) 的样子:

[{"ImageName":"https://domain.com/test.jpg","XPos":"347.98614501953125","YPos":"435.45140838623047","Height":"20","Width":"80.39999999999999"}] 

    [HttpPost]
    public JsonResult Create(Image i) {
         //p always has null values
    }

为什么我的视图模型总是包含空值?

使用 .ajax 发布到 MVC 4 控制器时,ViewModel 始终为 null

我认为您的错误是您正在使用数组。尝试这样。

var parameters = {
    ImageName: $('#imagename').val(),
    XPos: $('#xpos').val(),
    YPos: $('#ypos').val(),
    Height: $('#height').val(),
    Width: $('#width').val()
};

或者将输入参数更改为

public JsonResult Create(IEnumerable<Image> i)

这是一个对象的 Javascript 数组。 这与方法的签名不匹配。

[
  {
    "ImageName":"https://domain.com/test.jpg",
    "XPos":"347.98614501953125",
    "YPos":"435.45140838623047",
    "Height":"20",
    "Width":"80.39999999999999"
  }
] 

我将开始使用您正在使用的框架的一些内置功能来完成繁重的工作。

在您看来:

@Html.HiddenFor(m => m.ImageName);

在Jquery中:

$('form').submit(function () {
    var serializedForm = $(this).serialize();
    console.log(serializedForm );
    $.ajax({
        url: '@Url.Action("Create", "Home")',
        type: 'Post',
        data: serializedForm ,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            //yadda
        },
        error: function (xhr, status, error) {
          //yadda
        }
    });