Getting Null Value in List When Passing by Ajax Call to MVC Controller

getting null value in list when passing by ajax call to mvc controller

Use : [HttpGet] on the method AddTiles as you have used type: "GET" on the Ajax hit.

[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}

If Still doesn't works then try type: "POST" on Ajax hit and on method use [HttpPost]

[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}

mvc controller pameter getting null value in ajax call

Rather than using:

data: item.Id(),

I'd suggest using:

data: { id: item.Id()},

This way the id value is associated with the id name - allowing model binding to work correctly.

pass a list of objects via ajax to a MVC controller always sends null

This is a new answer. Originally, I was getting null, like you. But, now it works the way you want (array of complex objects). Please get this to work for you. If you can't get it to work, although it should, I can create an ASP.NET Fiddle.

public class RecievedTransactions
{
public int numReceived { get; set; }
public int transactionID { get; set; }
}

public class HomeController : Controller
{
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions) // MyArray MyArray
{
return;
}

//you use your own action name
public ActionResult Tut133()
{
return View();
}

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut132</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});

$.ajax({
//!!changing your url
//url: './ReceivePOLines',
url: "/Home/ReceivePOLines",
type: "Post",
cache: false,
//data: JSON.stringify({ MyArray: items }),
data: JSON.stringify(items),
//expecting back from server-need to remove since we are not getting back data from server
//dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
//alerting success instead of opening window
alert("success");
//window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
})
</script>
</head>
<body>
<table id="grid">
<tr>
<td><input type="text" id="NumReceived1" value="10000" /></td>
<td><input type="text" id="item_TransactionID1" value="10661768" /></td>
</tr>
<tr>
<td><input type="text" id="NumReceived2" value="10000" /></td>
<td><input type="text" id="item_TransactionID2" value="10661769" /></td>
</tr>
</table>
<input type="button" id="theButton" value="Go" />
</body>
</html>

ASP.NET MVC - Ajax passing null value to controller

Below is a work demo, you can refer to it.

Change ajax like below:

    ...
var Table={};
var tableName=$("#tableName").val();
Table.TableName=tableName;
Table.Columns=Columns;
console.log(JSON.stringify(Table));


$.ajax({
url:'/Home/Createtable',
type:'POST',
data:Table,
success:function(data){alert("success")},
error:function(){alert("error")}
});

In HomeController:

       public IActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult CreateTable(Table table, List<Column> Columns)
{
var ccc = 0; // do your staff...
return Json(ccc);
}

Result:

Sample Image

Object is null when passing from AJAX to Controller

Use [FromBody] to explicitly tell the model binder where to look for data to bind

public string RemoveImage([FromBody]UserWithImageModel input)

Also the data is not being sent in the correct format.

Change

input = JSON.stringify({'input': input }); 

to just

input = JSON.stringify(input);

Reference Model Binding in ASP.NET Core

Jquery Ajax call passed parameter always null in Asp.net MVC Core

You probably don't need to specify that you are sending dataType of json. I have tried the below and it worked

    function SetCurrentPageNameSession(currentPageName, isBookMarkPage) {
if(isBookMarkPage==undefined)
isBookMarkPage = false;
var url = baseUrl+"Manage/HighlightCurrentMenu/";
$.ajax({
type: "POST",
data: { CurrentPage: currentPageName, IsBookMark: isBookMarkPage },
url: url,
success: function (data) {
var res = data.d;
},
error: function (xhr, ajaxOptions, thrownError) {

}
});
}

List passed to controller via AJAX is null

When using contentType: 'application/json', you need to send data as the JSON string so that model binder will be able to map it.

You should be sending complex data via POST method, not GET. GET method is fine for sending small lean-flat view model with few properties. These will be send as query string by the $.ajax method. In your case, your data is not a flat-lean view model. So you should use POST as the method so that $.ajax will send the data in request body.

I also recommend you to use the Url.Action helper method to generate the correct relative url to the action method.

var urlToSave="@Url.Action("SaveSpec","Dpv")";
// use urlToSavefor the ajax call

$.ajax({
type: 'POST',
contentType: 'application/json',
url: urlToSave,
data: JSON.stringify(alarms)
}).done(function (partialViewResult) {
$('#statusMsg').html(partialViewResult);
}).always(function(result) {
console.log(result);
});

Also make sure your aciton method is POST

[HttpPost]
public ActionResult SaveSpec(IEnumerable<DpvItemLiteVm> alarms)
{
// to do : return something
}

Now the model binder will be able to read the request body and map it to the IEnumerable<DpvItemLiteVm> parameter you have.

Data pass from AJAX call to Controller but getting null values

For one, make your life easier by changing your parameter list in c# to a single class (in my example DTO just means Data Transfer Object):

public class VisitorDto 
{
public string visitpurpose {get;set;}
public string txt_visitor_name {get;set;}
public string txt_company_name {get;set;}
public string txt_emp_name {get;set;}
public string txt_phone {get;set;}
public string txt_designation {get;set;}
public string txt_address {get;set;}
public string txt_country_name {get;set;}
public string txt_state_name {get;set;}
public string txt_city_name {get;set;}
public string txt_emp_number {get;set;}
}

And have that in your method like:

public ActionResult SaveVisitorEntry(VisitorDTO model){
...
}

You could also then remove the prefixing of txt_ as it's a bit cumbersom but I'll leave that up to you.

It might just work after that.

Since in your Ajax class your Data: is an object as you've declared it like
Data: {}.

{} - is object syntax in javascript. So likely the reason it's null when arriving at your controller is because you've sent an object but the controller is expecting strings.

asp mvc controller receiving null values from ajax

Try this
uncomment //contentType: "application/json;",

And send data with JSON.stringify(data)

data: JSON.stringify(data)

PS: Best practice for url : url: "@Url.Action("method","controller")"



Related Topics



Leave a reply



Submit