behi behi behi behi - 1 year ago 62
jQuery Question

Why i get null in controller when call in ajax mvc?

I want to call controller with

in mvc
for that purpose write this code in view page:

$("#dbbutton").click(function (e) {

//Save DB NAME
var serviceURL = '/DDRS/SaveDBName';
type: "POST",
url: serviceURL,
data: JSON.stringify({ value:$("#DBName").val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
function successFunc(data, status) {
function errorFunc() {

and this is my action method in

public ActionResult SaveDBName(string DataBaseName)
string test = DataBaseName.Trim();
string sep = test.Substring(0, test.IndexOf(","));

return Json(test, JsonRequestBehavior.AllowGet);

but i get null error in
in this line:

string test = DataBaseName.Trim();

What happen?How can i solve that problem?thanks.

Answer Source

You have this issue because you are not sending the data in the format in which ASP.Net MVC expect. ASP.Net MVC need some special format when dealing value like string and value type (int, bool etc) parameter when they're used directly as parameter with POST method.

Your controller use a primtiive type but you are sending just

data: JSON.stringify({ value:$("#DBName").val() })

value is not the name of your parameter then it will not bind it to your DataBaseName parameter. Even if you replace value with the correct parameter name it will not work.

To make it work you must use the below code as data in your jQuery ajax request:

data: { "": $("#DBName").val() }

Notice that the property name is empty that will tell jQuery to send the data in this format


With that format, ASP.Net MVC can bind it to your parameter correctly.

To prevent that issue always use a ViewModel.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download