How to send data in jquery.post to mvc controller which use ViewModel as parameter?

前端 未结 2 1989
萌比男神i
萌比男神i 2020-12-02 13:28

I am writing application with asp.net mvc. I have controller with action, which use some ViewModel as parameter. How to send form data with jquery post to that mvc controlle

2条回答
  •  星月不相逢
    2020-12-02 14:10

    var myData = {
                  Parameter1: $("#someElementId").val(),
                  Parameter2: $("#anotherElementId").val(),
                  ListParameter: { /* Define IEnumerable collections as json array as well */}
                  // more params here
                 }  
    $.ajax({
        url: 'someUrl',
        type: 'POST',
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify(myData)
    });  
    
    
    [HttpPost]
    public JsonResult Create(CustomViewModel vm)
    {
        // You can access your ViewModel like a non-ajax call here.
        var passedValue = vm.Parameter1;
    }
    

    You can also serialize the whole form and pass it to your controller's action method. In you ajax call:

    data: $('form').serialize()
    

提交回复
热议问题