JSON将数据发布到mvc控制器

时间:2012-12-01 20:22:58

标签: c# asp.net-mvc json postback

我有一个包含Person和Address的实体类。

public class Person
{
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public List<Address> Addresses { get; set; }
}

public class Address
{
   public string ZipCode { get; set; }
   public string City { get; set; }
   public string State { get; set; }
   public string Country { get; set; }
}

在我看来,我会显示一些复选框。

@model DataContext.Models.Persons

@{
    ViewBag.Title = "Person list";
}

@using (Html.BeginForm("Update", "Test", FormMethod.Post))
{

    <div id="personContainer">
        @foreach(var t in Model.Person)
        {
            <input type="checkbox" value="@t.ID" name="@t.FirstName ">@t.FirstName <br />
        }
    </div>
    <p>
        <input type="submit" id="save">
    </p> 
}

我的控制器看起来像这样:

[HttpPost]
public JsonResult Update(Person p)
{

   return Json( new { redirectTo = Url.Action("Index") });
}

我要发布的数据必须是强类型的。 如何使用JSON将数据(在本例中为所有复选框)发回到“更新”控制器?

2 个答案:

答案 0 :(得分:2)

您需要为视图模型的每个属性输入一个输入。

每个输入的name属性需要与MVC的属性名称相同才能识别它。

例如:

@model Person

@using (Html.BeginForm("Update", "Test", FormMethod.Post))
{
    @Html.HiddenFor(model => model.ID)

    <input type="checkbox" value="@model.FirstName" name="FirstName ">@model.FirstName <br />
    <input type="checkbox" value="@model.LastName" name="LastName ">@model.LastName <br />
    @Html.EditorFor(model => model.Addresses)

    <input type="submit" id="save">
}

对于地址,创建一个编辑器模板,剃刀引擎将意识到该属性是可枚举的。

它会为名称属性添加可枚举的数字,如下所示:

<input id="addresses_0__city" type="text" value="City" name="addresses[0].city">

请注意,该名称具有数组样式。

  • 要创建编辑器模板,请在名为“EditorTemplates”的“共享”视图文件夹(或相关视图文件夹)中创建一个文件夹。
  • 创建名为Address的部分视图(与类型相同)。
  • 为每个地址添加要查看的HTML:

    @model Address
    
    @Html.CheckBox("ZipCode", false, new { value = Model.ZipCode}) @Model.ZipCode
    <br />
    @Html.CheckBox("City", false, new { value = Model.City}) @Model.City
    <br />
    @Html.CheckBox("State", false, new { value = Model.State}) @Model.State
    <br />
    @Html.CheckBox("Country", false, new { value = Model.Country}) @Model.Country
    <br />
    

这将有效,但它不会将表单发布为JSON。如果您需要专门发布为JSON,您可以在AJAX POST上将表单数据转换为JSON:

$.ajax("/Test/Update",
{
    type: "post",

    data: JSON.stringify($('form').serializeObject()), // converting to JSON
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (data) {}      
    error: function () {}
});

对于JSON.stringify,表单首先使用以下内容放入对象形式:

$.fn.serializeObject = function () {
    var obj = {};
    var arr = this.serializeArray();

    $.each(arr, function () {
        var splt = this.name.split(".", 2);
        if (splt.length === 2) {
            if (obj[splt[0]] === undefined) {
                obj[splt[0]] = {};
            }
            obj[splt[0]][splt[1]] = this.value || '';
        }
        else if (obj[this.name] !== undefined) {
            if (!obj[this.name].push) {
                obj[this.name] = [obj[this.name]];
            }
            obj[this.name].push(this.value || '');
        }
        else {
            obj[this.name] = this.value || '';
        }
    });
    return obj;
};

答案 1 :(得分:0)

设置一个jquery方法在表单submit上运行,以便在Begin表单中将序列化表单发送给控制器

$('formSelector').submit(function () {
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.Success == true) {

                }
                else {
                    $('#Error').html(result.Html);
                }
            }
        });
    }
    return false;
});
相关问题