Search code examples
jqueryajaxasp.net-mvc

Sending data from ajax to controller is not getting the value to the controller


I've been trying to pass JSON data into MVC controller, which hasn't worked so far.

The controller method have the property as model like newObject like as follows

[HttpPost]
public ActionResult Create(NewObject newObject)
{
     try
     {
         //_deviceMangementService.CreateDevices(newObject.Name,1); // name is always null here
         return RedirectToAction(nameof(Index));
     }
     catch
     {
         return View();
     }
}

The key point to solve this issue out there was to stringify the JSON object, define a model and get the parameter as the defined model, or define contentType. When it hits the controller i am getting null values in the name and DeviceId as 0.

I did those but defining a model for passing JSON into controller.

var newObject= {};
        newObject.DeviceId=1;
        newObject.Name = "testds";
$.ajax({
     type: 'POST',         
     url: '@Url.Action("Create","DeviceConfiguration")',
     data: { newObject: JSON.stringify(newObject) },
     dataType: 'JSON',
     contentType: 'application/json; charset=utf-8',
     success: function (data) {
         if (data.success) {
             alert('Saved');;
         }
     },
     error: function (e) {
         console.log(e);
     }
 });

And i am getting the payload from network like

newObject=%7B%22DeviceId%22%3A1%2C%22Name%22%3A%22testds%22%7D

Is there another way to get JSON data from Ajax call in a controller or what i did wrong i don't know. Please guide me.


Solution

  • I think you should change the data that is sent by ajax:

    data: JSON.stringify(newObject)
    

    so the controller can bind the properties in the model.