1

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)

3
  • Use WebAPI for that. Commented Oct 29, 2014 at 3:09
  • we dont use WebAPI in our project Commented Oct 29, 2014 at 3:12
  • Do you want to dynammically append values to your form & then want to submit it to server side? Commented Oct 29, 2014 at 3:43

1 Answer 1

1

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

}
Sign up to request clarification or add additional context in comments.

3 Comments

I dont want to make an AJAX call i want to send data on submit button
Then why you are constructing Javascript array in convertJqueryModelToMVC function ? How can you send the Javascript array to the controller with out using Ajax ?
I created dynamic hidden fields with name ="[0].Id" & "[0].Name" & i got the Model in HttpPost

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.