JSON post data to mvc controller

断了今生、忘了曾经 提交于 2020-01-06 20:06:16

问题


I got an entity class that contains a Person and 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; }
}

In my view i display a few checkboxes.

@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> 
}

My controller looks like this:

[HttpPost]
public JsonResult Update(Person p)
{

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

The data i want to post must be strongly typed. How can i post back the data (in this case all checkboxes) to the 'update' controller with JSON?


回答1:


You need to have an input for each property of your view model.

The name attribute on each input needs to be the same as the property name for MVC to recognise it.

For instance:

@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">
}

For the address, create an editor template, and the razor engine will realise that the property is an enumerable.

It will add enumerable numbers to the name attributes like this:

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

Notice that the name has a array style.

  • To create the editor template, make a folder in your "Shared" view folder (or the relevant view folder) named "EditorTemplates".
  • Create a partial view named Address (the same as the type).
  • Add the HTML you want to see for each Address:

    @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 />
    

This will work, but it wont post the form as JSON. If you need to specifically post as JSON you could convert the form data to JSON on an AJAX POST:

$.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 () {}
});

To JSON.stringify the form is first put into object form using this:

$.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;
};



回答2:


Setup a jquery method to run on the form submit to send the serialised form to the controller in the Begin Form

$('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;
});


来源:https://stackoverflow.com/questions/13663383/json-post-data-to-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!