0

我的 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
    }

为什么我的 ViewModel 总是包含空值?

4

2 回答 2

4

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

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

或者将输入参数更改为

public JsonResult Create(IEnumerable<Image> i)
于 2013-10-23T19:32:53.410 回答
2

这是一个对象的 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
        }
    });
于 2013-10-23T19:24:36.500 回答