Ulhas Tuscano
Ulhas Tuscano

Reputation: 5620

Bind Jquery Array to ASP.NET MVC Model

I have emp class with Id & Name properties

class Emp
{
   int id{get;set;}
   int Name{get;set;}
}

@model List<Emp>
<script>
    function convertJqueryModelToMVC()
    {
           var emps = [];
           emps.push({id:1,Name:"abc"});
           emps.push({id:2,Name:"xyz"});
           //logic for converting emps to List<emp> model
    }
</script>

I want to achieve this so that when i click on submit button all the form fields will be submitted in a single postback. This is just an example what i am trying to achieve (Note : I am aware standard MVC process)

Upvotes: 1

Views: 1445

Answers (1)

Hemant B
Hemant B

Reputation: 140

Pass Json Object from Javascript, The Model binder will automatically do its job. Like this.

var emps= [
        { id: 1, Name: 'name1' },
        { id: 2, Name: 'name2' },
        { id: 3, Name: 'name3' }
    ];      

    emps= JSON.stringify({ 'empList': emps});

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/Employee',
        data: emps,
        success: function () {          
            $('#result').html('successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 

In your controller

public ActionResult Employee(List<Emp> empList)
{

//Your Logic

}

Upvotes: 1

Related Questions