Send array from view to controller as class – ASP.NET Core.

Example

To send array values from table in view to controller as array class I’ll use JQuery and Ajax. For the needs of the example I generate table in view.

<table class="table table-bordered">
    <tr>
        <th>
            Name
        </th>
        <th>
            Value
        </th>
    </tr>
    @for (int i = 0; i < 10; i++)
    {
        <tr>
            <td class="Name">
                Name @i
            </td>
            <td class="Val">
                Value @i
            </td>
        </tr>
    }
</table>

table jquery

Then I create array in javascript and push all value from table to this array. The name in the array should be the same as the names in the class that will be the parametr in the controller.

        var arr = [];
        $('.Name').each(function () {
            var nam = $(this).text().trim();
            var val = $(this).siblings('.Val').text().trim();
            arr.push({ Name: nam, Value: val });
        });

And model class:

public class SampleClass
{
    public string Name { get; set; }
    public string Value { get; set; }
}

Next we use ajax to send the array to controller.

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "/Home/Values",
    data: JSON.stringify(arr),
    dataType: "json",
    success: function (response, data) {
        alert(response.someValue);
    },
    error: function (err) {
    }
});

And our controller look like this.It is important to add [FromBody] if we use ASP.NET Core.

[HttpPost]
public IActionResult Values([FromBody] SampleClass[] model)
{
    return Json(new { someValue = "It's ok" });
}

send values from view to controller

By using these methods we can easily send large amounts of data in one class without creating controllers with a high number of parametrs.

Link to project.

Leave a Reply

Your email address will not be published. Required fields are marked *