Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post a json object to mvc controller with jquery and ajax

Tags:

I am trying to submit some values from a form to my mvc controller.

Here is my controller:

 //Post/ Roles/AddUser     [HttpPost]            public ActionResult AddUser(String json)     {         Log.submit(json);                     return View();     } 

here is the js:

<script> function submitForm() {      var usersRoles = new Array;     $("#dualSelectRoles2 option").each(function () {         usersRoles.push($(this).val());     });     console.log(usersRoles);      jQuery.ajax({         type: 'POST',         url: "@Url.Action("AddUser")",         contentType: "application/json; charset=utf-8",         datatype: 'json',         data: JSON.stringify(usersRoles),         success: function (data) { alert(data); },         failure: function (errMsg) {             alert(errMsg);         }     }); } 

When I debug on the controller I get my parameter to be null? The console.log(usersRoles) gives me data.

What am I doing incorrectly?

How can I receive a json object in the controller?

like image 408
Zapnologica Avatar asked Feb 05 '14 07:02

Zapnologica


People also ask

How to send JSON data to controller using AJAX in MVC?

Create target "JSON object Mapper" object class file according to the business requirements. Create a "Controllers\HomeController. cs" file with default Index method and GetData(...) method with string type input query parameters for Ajax call with following lines of code i.e.

How pass JSON object in URL in asp net?

How pass JSON object in URL in asp net? For passing the json you need to create a class object and set the value and Serialize to json string and pass to the url. For more details refer below sample code. string apiUrl = “http://localhost:26404/api/CardAPI” ; JsonInput input = new JsonInput();

How show JSON data table in HTML MVC?

Right click on Controller folder in the created MVC application, give the class name Home or as you wish and click OK. In the above controller class JsonResult method EmpDetails we have added the records into the Generic list and returning it as JSON to avoid database query for same result.


2 Answers

I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -

<script src="~/Scripts/jquery-1.10.2.min.js"></script> <script>     function submitForm() {         var roles = ["role1", "role2", "role3"];          jQuery.ajax({             type: "POST",             url: "@Url.Action("AddUser")",             dataType: "json",             contentType: "application/json; charset=utf-8",             data: JSON.stringify(roles),             success: function (data) { alert(data); },             failure: function (errMsg) {                 alert(errMsg);             }         });     } </script>  <input type="button" value="Click" onclick="submitForm()"/> 

And the controller action is going to be -

    public ActionResult AddUser(List<String> Roles)     {         return null;     } 

Then when you click on the button -

enter image description here

like image 70
ramiramilu Avatar answered Sep 19 '22 06:09

ramiramilu


instead of receiving the json string a model binding is better. For example:

[HttpPost]        public ActionResult AddUser(UserAddModel model) {     if (ModelState.IsValid) {         return Json(new { Response = "Success" });     }     return Json(new { Response = "Error" }); }  <script> function submitForm() {         $.ajax({         type: 'POST',         url: "@Url.Action("AddUser")",         contentType: "application/json; charset=utf-8",         dataType: 'json',         data: $("form[name=UserAddForm]").serialize(),         success: function (data) {             console.log(data);         }     }); } </script> 
like image 28
Shibbir Ahmed Avatar answered Sep 20 '22 06:09

Shibbir Ahmed