Search code examples
c#jqueryajaxjsonwebmethod

How exactly does a JSON.stringify automatically map to my DTO


I have an object in jquery:

function SaveRequest() {
var request = BuildSaveRequest();

$.ajax({
    type: "POST",
    processData: false,
    data: JSON.stringify({'model':request}),
    url: "somepage.aspx/JsonSave",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(response, status, xhr) {
    },
    error: function (res, status, exception) {
    }
});
return false;
}

function BuildSaveRequest() {

var request = {
    customerName: $("#CustomerName").val(),
    contactName: $("#ContactName").val(),
};

return request;
}

And I have the following c# code:

[WebMethod]
public static string JsonSave(MyModel model)
    {
    }
}

public class MyModel 
{
    public string CustomerName { get; set; }
    public string ContactName { get; set; }
}

When the ajax call goes, the web method JsonSave automatically place the values (CustomerName, & ContactName) from the jquery object 'request' into the appropriate properties in object 'model'. How does it know to do that???


Solution

  • Added answer from comments:

    Model Binders are a beautiful thing.

    I would recommend reading the source found here this is for MVC but I'm pretty sure it acts the same in webforms as well.

    It is really smart and checks the in request for the data so it doesn't really matter if you use webforms or mvc. You can even create our own.