Post JSON array to mvc controller Post JSON array to mvc controller arrays arrays

Post JSON array to mvc controller


There are lots of issues with your code. Let's start with the markup. You have a table and inside each row of this table you are including hidden fields. Except that you have hardcoded the id attribute of those hidden elements meaning that you could potentially end up with multiple elements with the same id in your markup which results in invalid markup.

So let's start by fixing your markup first:

@foreach (var t in Model.Types.ToList()){    <tr>        <td>                              <input type="hidden" value="@t.TransID" name="TransID" />            <input type="hidden" value="@t.ItemID" name="ItemID" />            <input type="hidden" value="@t.TypeID" name="TypeID" />        </td>    </tr>}

Alright, now you have valid markup. Now let's move on to the javascript event which will be triggered when some submitTest button is clicked. If this is the submit button of the form I would recommend you subscribing to the .submit event of the form instead of the .click event of its submit button. The reason for this is because a form could be submitted for example if the user presses the Enter key while the focus is inside some input field. In this case your click event won't be triggered.

So:

$(document).ready(function () {    $('form').submit(function () {        // code to follow        return false;    });});

Alright, next comes the part where you need to harvest the values of the hidden elements which are inside the table and put them into a javascript object that we will subsequently JSON serialize and send as part of the AJAX request to the server.

Let's go ahead:

var parameters = [];// TODO: maybe you want to assign an unique id to your table element$('table tr').each(function() {    var td = $('td', this);    parameters.push({        transId: $('input[name="TransID"]', td).val(),        itemId: $('input[name="ItemID"]', td).val(),        typeId: $('input[name="TypeID"]', td).val()    });});

So far we've filled our parameters, let's send them to the server now:

$.ajax({    url: this.action,    type: this.method,    data: JSON.stringify(parameters),    contentType: 'application/json; charset=utf-8',    success: function (result) {        // ...    },    error: function (request) {         // ...    }});

Now let's move on to the server side. As always we start by defining a view model:

public class MyViewModel{    public string TransID { get; set; }    public string ItemID { get; set; }    public string TypeID { get; set; }}

and a controller action that will take a collection of this model:

[HttpPost]public ActionResult Update(IList<MyViewModel> model){    ...}

And here's the final client side code:

$(function() {    $('form').submit(function () {        if ($(this).valid()) {            var parameters = [];            // TODO: maybe you want to assign an unique id to your table element            $('table tr').each(function() {                var td = $('td', this);                parameters.push({                    transId: $('input[name="TransID"]', td).val(),                    itemId: $('input[name="ItemID"]', td).val(),                    typeId: $('input[name="TypeID"]', td).val()                });            });            $.ajax({                url: this.action,                type: this.method,                data: JSON.stringify(parameters),                contentType: 'application/json; charset=utf-8',                success: function (result) {                    // ...                },                error: function (request) {                     // ...                }            });        }        return false;    });});

Obviously if your view model is different (you haven't shown it in your question) you might need to adapt the code so that it matches your structure, otherwise the default model binder won't be able to deserialize the JSON back.


There is another simpler way: using Query String to send your data. If you got intrested, your current approach is wrong because the JSON array data type is string not CustomTypeModel.

First of all, remove the data ajax option. We don't need that anymore.

Second, change your controller like the following:

[HttpPost]public ActionResult Update(string json){    // this line convert the json to a list of your type, exactly what you want.    IList<CustomTypeModel> ctm =          new JavaScriptSerializer().Deserialize<IList<CustomTypeModel>>(json);    return RedirectToAction("Index");}

Note1: It's important that names of your CustomTypeModel properties be the same as what you enter as the JSON elements. So, your CustomTypeModel should be like this:

public class CustomTypeModel{    // int, or maybe string ... whatever you want.    public int TransIDs { get; set; }    public int ItemIDs { get; set; }    public int TypeIDs { get; set; }}

Note2: This approach is useful when you want to send the data through query strings. So, your url can be like this:

url: '/controller/action?json=' + JSON.stringify(trans)


I think you doing thing's in a bit wrong manner for MVC world.If you have a proper model for binding your data with - you better using helpers going from the box instead of using "handmade" JavaScript. Take a look to HtmlHelper or AjaxHelper if you need async calls.

And bind you data to model using @Html.TextBoxFor() notation inside @Html.BeginForm block That will simplify your code much and reduce amount of javascript, which is much better for maintenance.

On the server part you need to implement custom model binder and change settings to make handle request for current controller action via your model binder. It will take you to write some serverside code, but statically typed code looks easier to code and test or me, and it's better suit or your application needs, because I prefer JavaScript doing things it should do = > managing UI, but not constructing model for correct parsing on the serverside. It's better suit for single responsibility principle.

See this video, this is simple tutorial how to do that