Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Multiple Parameters from ajax call to MVC Controller

Tags:

I have the controller like the below:

public ActionResult Save(string input, string name) {     //Some code     return PartialView(); } 

And I need an ajax call to this controller method and pass the two arguments input and value

And my ajax call is like the below:

$.ajax({     url: '/Home/Save',     type: 'POST',     async: false,     dataType: 'text',     processData: false,     data: "input=" + JSON.stringify(data) + "&name =" + $("#name").val(),     success: function (data) {     } }); 

I am unable to pass the value to the name parameter.. the value in the name parameter is becoming null .. please help me .. Thanks in advance

like image 841
DS kumar Avatar asked Nov 25 '13 13:11

DS kumar


People also ask

How pass JSON data to AJAX to controller?

ajax({ type: "POST", url: "DATACRUD. json", data: JSON. stringify({data:"test"}), contentType: "application/json; charset=utf-8", dataType: "json", async: false, //_async, success: function (result) { } }); Ajax successfully invokes the action in a controller, but the parameter is null.


2 Answers

You're making an HTTP POST, but trying to pass parameters with the GET query string syntax. In a POST, the data are passed as named parameters and do not use the param=value&foo=bar syntax. Using jQuery's ajax method lets you create a javascript object with the named parameters, like so:

$.ajax({   url: '/Home/SaveChart',   type: 'POST',   async: false,   dataType: 'text',   processData: false,       data: {        input: JSON.stringify(IVRInstant.data),        name: $("#wrkname").val()   },   success: function (data) { } }); 
like image 191
xdumaine Avatar answered Sep 28 '22 02:09

xdumaine


In addition to posts by @xdumain, I prefer creating data object before ajax call so you can debug it.

var dataObject = JSON.stringify({                     'input': $('#myInput').val(),                     'name': $('#myName').val(),                 }); 

Now use it in ajax call

$.ajax({           url: "/Home/SaveChart",           type: 'POST',           async: false,           dataType: 'json',           contentType: 'application/json',           data: dataObject,           success: function (data) { },           error: function (xhr) { }            )}; 
like image 28
Himalaya Garg Avatar answered Sep 28 '22 03:09

Himalaya Garg