model is null when passed to ActionResult - javascript

Can anyone spot why my model would be null when it's passed to the controller? I put an alert in the ajax call to check the value there and it look correct, but a breakpointon the 1st line on the controller ActionResult shows it is null.
thanks in advance
ajax call
function DeleteFromList(_id) {
var _model = $('#createLPathForm').serialize();
alert(_model);
event.preventDefault();
$('#createLPathForm').validate();
if $('#createLPathForm').validate()) {
var request = $.ajax({
type: "POST",
url: "/umbraco/Surface/CreateLPath/DeleteItems",
dataType: 'json',
data: { 'model': _model, 'id': mId },
success: function (data) {
$("#lpPartial").html(data);
},
error: function (data) {
//$('#failModal').removeClass("d-none").addClass("d-block");
}
})
}
}
Controller
[HttpPost]
[ActionName("DeleteItems")]
public ActionResult ("DeleteItems")](CreateLPathModel _model, string id)
{
List<ModuleItems> items = _model.SelectedModuleList;
ModuleItems itemToDelete = new ModuleItems();
foreach (var item in items)
{
if (item.ArticleGuid == id)
{
itemToDelete = item;
}
}
_model.SelectedModuleList.Remove(itemToDelete);
itemToDelete.isSelected = false;
_model.SelectModulesList.Add(itemToDelete);
foreach (var key in ModelState.Keys.Where(m => m.StartsWith("SelectModulesList")).ToList())
ModelState.Remove(key);
foreach (var key in ModelState.Keys.Where(m => m.StartsWith("SelectedModuleList")).ToList())
ModelState.Remove(key);
return PartialView("~/Views/Partials/LearningPaths/_CreateLPath.cshtml", _model);
}

You are serializing your form and send as a property to your data model. In order to solve your problem, you can set data property with your _model variable and send your mId variable as query string :
function DeleteFromList(_id) {
var _model = $('#createLPathForm').serialize();
alert(_model);
event.preventDefault();
$('#createLPathForm').validate();
if $('#createLPathForm').validate()) {
var request = $.ajax({
type: "POST",
url: "/umbraco/Surface/CreateLPath/DeleteItems?id=" + mId,
dataType: 'json',
data: _model,
success: function (data) {
$("#lpPartial").html(data);
},
error: function (data) {
//$('#failModal').removeClass("d-none").addClass("d-block");
}
})
}
}

It can be done with:
Create a class with below structure:
public class RootObject
{
public CreateLPathModel _model {get; set;}
public string id {get; set;}
}
Then Controller method will be:
[ActionName("DeleteItems")]
public ActionResult ("DeleteItems")]([FromBody] RootObject obj)
{
// use Obj._model etc
}
and make sure while passing data in the AJAX call:
data: JSON.stringify({ 'model': _model, 'id': mId });

Related

Return parameter null in controller from ajax

I don't know what happened the value sent to the controller is always null, even though in the console.log the value is there, please I need help
this is my ajax:
$('#ddlItemName').change(function () {
var ItemCode = $('#ddlItemName').text();
if (ItemCode != '') {
var RequestParam = {
search: ItemCode
}
console.log(RequestParam);
$.ajax({
url: '/Order/CustomerItemOrders',
type: 'POST',
data: JSON.stringify(RequestParam),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data[0].Name);
},
error: function (data) {
toastr.error(data);
}
});
}
$('#ddlItemName').text('');
});
This is my controller :
[HttpPost]
public JsonResult CustomerItemOrders([FromBody] string search)
{
var result = _order.BindCustomerOrders(search);
return Json(result.data);
}
This is my error :
enter image description here
I've tried adding '[FromBody]' but the value parameter still doesn't get sent
I recomend you add the parameter to query
If you insist on pass the value with request body
Try creat a model:
public class SomeModel
{
public string search{get;set;}
}
in your controller:
public JsonResult CustomerItemOrders([FromBody] SomeModel somemodel)
{
.......
}

Ajax POST an object with javascript, but the value in backend is null, why?

So on button click there is a function sendEmail(). Alert is working fine, I can see my datas there. But on backend I can't see anything, just everything is null.
function sendEmail() {
var datas = new Object();
datas.mail = $('#contactDropdownList').val();
datas.mailobject = $('#emailObject').val();
datas.text = $('#emailText').val();enter code here
alert(datas.mail + datas.mailobject + datas.text);
$.ajax({
type: "POST",
dataType: "json",
url: "/Email/sendEmail",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ items: datas }),
success: function (data) {
console.log(data);
//do something with data
},
error: function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
}
});
}
C# code:
public class MyClass
{
public string Email { get; set; }
public string Object { get; set; }
public string Text { get; set; }
}
[HttpPost]
public IActionResult sendEmail(MyClass items)
{
return Json(new { data="Ok" });
}
items.Email, items.Object and items.Text are null.
And the return valu is null as well, because in javascript success: function (data) { console.log(data);
is empty string.
What can be the problem? Thank you!
Model binder expects json content to match C# class. Your datas object should look like that
var datas = {
email: $('#contactDropdownList').val(),
object: $('#emailObject').val(),
text: $('#emailText').val()
}
Since you wrapped your object ({ items: datas }), you may think it will be mapped to sendEmail(MyClass items), but in reality items name does not matter, you can change variable name to any other name you like
Make sure you apply [FromBody] attribute to your parameter like that
[HttpPost]
public IActionResult sendEmail([FromBody]MyClass items)
Complete demo:
<script>
function sendSmth() {
var data = {
Email: 'email',
Object: 'object',
Text: 'text'
};
$.ajax({
type: "POST",
dataType: "json",
url: "/home/index",
contentType: "application/json",
data: JSON.stringify(data),
success: function (datas) {
console.log(datas)
}
})
}
</script>
And controller
[HttpPost]
public IActionResult Index([FromBody]MyClass obj)
{
return View();
}
As someone has noted, you have a mismatch between what you're sending to the controller and what the model the modelbinder is expecting. You can also vastly simply your AJAX code:
function sendEmail() {
var data = {
Email: $('#contactDropdownList').val(),
Object: $('#emailObject').val(),
Text: $('#emailText').val()
};
$.post("/Email/sendEmail", data)
.done(function (response) {
console.log(response);
//do something with response
})
.fail(function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
});
}
You don't really need to specify the content type or data type - the $.post helper's defaults work just fine for what you've shown.

Ajax call hits with null values

I have a array and I get data from the array and going to pass it to the controller through ajax call.
But the problem is it hits the controller side with all the null values.(Data not passes,null passes )
Client Side Code
for (var j = 0; j < NewsGlobalArray.length; j++) {
var NewsRequestModel = {
DESCRIPTION: NewsGlobalArray[j]['DESCRIPTION'] // news description comes here.i checked it with console.log
}}
$.ajax({
url: $('#addNewsRequest').val(),
type: "POST",
data: { newsRequest: NewsRequestModel },
dataType: "json",
success: function (referenceNo) {
//success
}
});
}
My Controller
[HttpPost]
public JsonResult AddNewsRequest(NewsRequestModel newsRequest) // hits here with null values
{
//Some coding goes here.
}
My Model
public class NewsRequestModel
{
public int NEWSREQUESTID { get; set; }
public string DESCRIPTION { get; set; }
}
Try this: just add traditional:true in ajax call
$.ajax({
type: "POST",
url: $('#addNewsRequest').val(),
data: JSON.Stringify({ newsRequest: NewsRequestModel }),
dataType: "json",
traditional:true,
success: function (res) {
//do something
}
});
I think you need to this:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
then pass myObject to ajax call and get on controller by name.

Passing two parameters to another controller with js

This is a button passing parameter values to another controller. It works perfectly for passing one value to the CarController but when I pass two I see it passing in the vehicle page but the breakpoint on the CarController shows that the vin_num value passed but the stock_num is null
Passing one param, works perfectly.
Vehicle.js
$(".button").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "/Cars/setD",
data: JSON.stringify({ vin_num: this.id }),
success: function (result) {
window.location.href = '/Cars/Index';
}
});
});
CarController.cs
public JsonResult setD(string vin_num)
{
Session["vin_num"] = vin_num;
return Json(true, JsonRequestBehavior.AllowGet);
}
What I tried, for passing two values.
$(".button").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "/Cars/setD",
data: JSON.stringify({ vin_num: this.id, stock_num: this.id2 }),
success: function (result) {
window.location.href = '/Cars/Index';
}
});
});
CarController.cs
public JsonResult setD(string vin_num, string stock_num)
{
Session["vin_num"] = vin_num;
Session["stock_num"] = stock_num;
return Json(true, JsonRequestBehavior.AllowGet);
}
You can use the Route attribute:
[Route("api/car/{param}/{paramTwo}")]
public JsonResult GetSomething(int param, int paramTwo) {
}
You can find more information about Attribute Routing in the following link
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
Create a class for the object then pass that object:
public class Stock
{
string vin_num { get; set; };
string stock_num { get; set; };
}
in controller:
public JsonResult setD(Stock stock)
{
and use it:
data: JSON.stringify(stock:{ vin_num: this.id, stock_num: this.id2 }),
Alternatively:
var mydata= {stock { vin_num: this.id, stock_num: this.id2 }};
...
data: JSON.stringify(mydata),

Trouble sending an array to a model in MVC

What I have:
A Model like this:
public class ProductModel
{
public string ProductName { get; set; }
public List<string> SkipUpdates { get; set; }
}
A controller method like this:
public ActionResult GetProductUpdates(ProductModel productModel)
{
return View("AddEdit");
}
Not doing anything for now just want to make sure that data from JS comes in correctly.
The JS:
function productModel() {
this.productName = "";
this.SkipUpdates = [];
}
Filling the model and AJAX:
var newProductModel = new productModel();
var options = $('#AdditionalSkipDates option');
var skipDates = [];
options.each(function (i, option) {
skipDates[i] = $(option).text();
});
newProductModel.productName = "ABC";
newProductModel.SkipUpdates = skipDates;
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: newProductModel,
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});
AdditonalSkip dates is a listbox with a bunch of dates in it.
What's happening:
The SkipUpdates array does have values which I can see in the browser's console.
Put a breakpoint in the controller and it hits the method.
The SkipUpdates value is null.
What's not happening:
How do I get the array to come-into the controller?
Thanks in advance.
Try to stringify the object before sending it:
$.ajax({
type: "GET",
url: urlToGetProductSchedule,
data: JSON.stringify(newProductModel),
dataType: "json"
}).success(function () {
}).fail(function (xhr) {
alert("Something went wrong!!!");
console.log(xhr.responseText);
});

Categories

Resources