behi behi behi behi - 1 month ago 6
jQuery Question

Why i get null in controller when call in ajax asp.net mvc?

I want to call controller with

ajax
in
asp.net mvc
for that purpose write this code in view page:


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

//Save DB NAME
var serviceURL = '/DDRS/SaveDBName';
$.ajax({
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) {
alert(data);
}
function errorFunc() {
alert('error');
}




and this is my action method in
DDRS
controller:


[HttpPost]
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
SaveDBName
in this line:


string test = DataBaseName.Trim();




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

Answer

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

='MyDatabaseNameWillGoHere'

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

To prevent that issue always use a ViewModel.

Comments