[asp.net-mvc] How to send a model in jQuery $.ajax() post request to MVC controller method

In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    //data:  ??????
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

Every time there is a post, I need to increment the value attribute in the model:

public ActionResult Modelpage(MyModel model)
    {                   
        model.value = model.value + 1;

        return PartialView("ModelPartialView", this.ViewData);
    }

But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?

This question is related to asp.net-mvc jquery asp.net-ajax

The answer is


In ajax call mention-

data:MakeModel(),

use the below function to bind data to model

function MakeModel() {

    var MyModel = {};

    MyModel.value = $('#input element id').val() or your value;

    return JSON.stringify(MyModel);
}

Attach [HttpPost] attribute to your controller action

on POST this data will get available


I have an MVC page that submits JSON of selected values from a group of radio buttons.

I use:

var dataArray = $.makeArray($("input[type=radio]").serializeArray());

To make an array of their names and values. Then I convert it to JSON with:

var json = $.toJSON(dataArray)

and then post it with jQuery's ajax() to the MVC controller

$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json, 
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});

Which sends the data across as native JSON data.

You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.

To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.

Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.

Article on MVC JSON deserialization


If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.

In our app, we do this with an extension method:

public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

On the view, we use it to render the model:

<script type="javascript">
  var model = <%= Model.ToJson() %>
</script>

You can then pass the model variable into your $.ajax call.


I think you need to explicitly pass the data attribute. One way to do this is to use the data = $('#your-form-id').serialize();

This post may be helpful. Post with jquery and ajax

Have a look at the doc here.. Ajax serialize


This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.

I am achieving this either by a double click event on a grid row or click event on a button of some sort.

@model TestProject.Models.TestModel

<script>

function testButton_Click(){
  var javaModel ={
  ModelId: '@Model.TestId',
  CreatedDate: '@Model.CreatedDate.ToShortDateString()',
  TestDescription: '@Model.TestDescription',
  //Here I am using a Kendo editor and I want to bind the text value to my javascript
  //object. This may be different for you depending on what controls you use.
  TestStatus: ($('#StatusTextBox'))[0].value, 
  TestType: '@Model.TestType'
  }

  //Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox 
    //selected value. This puzzled me due to the conversion to Json object in the Ajax call. 
  //By parsing the Type to an int this worked.

  javaModel.TestType = parseInt(javaModel.TestType);

  $.ajax({
      //This is where you want to post to.
      url:'@Url.Action("TestModelUpdate","TestController")', 
      async:true,
      type:"POST",
      contentType: 'application/json',
      dataType:"json",
      data: JSON.stringify(javaModel)
  });
}
</script>


//This is your controller action on the server, and it will autobind your values 
//to the newTestModel on post.

[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
 TestModel.UpdateTestModel(newTestModel);
 return //do some return action;
}

you can create a variable and send to ajax.

var m = { "Value": @Model.Value }

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    data:  m,
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

All of model's field must bo ceated in m.


The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.

As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.

For example, the Javascript:

var values = 
{
    "Name": "Chris",
    "Color": "Green"
}

$.post("@Url.Action("Update")",values,function(data)
{
    // do stuff;
});

The model:

public class UserModel
{
     public string Name { get;set; }
     public string Color { get;set; }
     public IEnumerable<string> Contacts { get;set; }
}

The controller:

public ActionResult Update(UserModel model)
{
     // do something with the model

     return Json(new { success = true });
}

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to asp.net-ajax

How to pass multiple parameters from ajax to mvc controller? window.open with target "_blank" in Chrome Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method Disable asp.net button after click to prevent double clicking How can I convince IE to simply display application/json rather than offer to download it? How to send a model in jQuery $.ajax() post request to MVC controller method How to post ASP.NET MVC Ajax form using JavaScript rather than submit button How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET? jQuery $(document).ready and UpdatePanels? ASP.NET MVC controller actions that return JSON or partial html