Return parameter null in controller from ajax - javascript

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)
{
.......
}

Related

What's the correct way to create class in JavaScript and pass that to MVC controller

I have a complex form with different tabs, so my ask is to save the entire form data to database on final save. I have the models as per my database as follows, posting sample class
public class VesselDetail
{
public string VesselName { get; set; }
}
public class MainModel
{
public VesselDetail VesselDetail { get; set; }
}
I have created JavaScript models as follows
class VesselDetail {
constructor() {
}
VesselName;
}
class MainModel {
constructor() {
this.VesselDetail = [];
}
}
On my save I am framing the data as follows
let data = new MainModel();
let vesselDetail = new VesselDetail();
vesselDetail.VesselName = "XYZ";
data.VesselDetail.push(vesselDetail);
$.ajax({
url: '/Controller/SaveFormData',
type: 'POST',
data: '{mainModel: ' + JSON.stringify(data) + '}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
},
error: function (request) {
hideSpinner();
}
});
My controller is as follows
[HttpPost]
public JsonResult PostUserData(MainModel mainModel)
{
return new JsonResult { Data = "OK" };
}
Somehow I am unable to see the vessel name that was given. I would like to know are my JavaScript models are correct or should I do any changes? Any better idea to make these models in JavaScript.
Don't hand-construct JSON, it's really easy to get it wrong. In this case, you haven't put the necessary " around mainModel in the JSON you're sending the server, which makes it invalid. As a result, the server won't be able to parse the JSON it receives.
$.ajax({
url: '/Controller/SaveFormData',
type: 'POST',
data: '{mainModel: ' + JSON.stringify(data) + '}',
// ^−−−−−−−−^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− missing quotes
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
},
error: function (request) {
hideSpinner();
}
});
Instead, let JSON.stringify do it for you:
$.ajax({
url: '/Controller/SaveFormData',
type: 'POST',
data: JSON.stringify({mainModel: data}),
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
},
error: function (request) {
hideSpinner();
}
});
Also, unless your server is returning JSON you're not using, you don't need dataType. (Even if it is, it should be returning the correct Content-Type header in which case dataType is redundant anyway.)
I also suggest either consistently using property declaration syntax (which is fairly new) or consistently not using it:
Not using it:
class VesselDetail {
}
class MainModel {
constructor() {
this.VesselDetail = [];
}
}
Using it:
class VesselDetail {
VesselName;
}
class MainModel {
VesselDetail = [];
}
Here's an example of the JSON that will be produced by your code with the changes above (I've used property declaration syntax — the second set of classes above — but they'll both produce the same thing):
class VesselDetail {
VesselName;
}
class MainModel {
VesselDetail = [];
}
let data = new MainModel();
let vesselDetail = new VesselDetail();
vesselDetail.VesselName = "XYZ";
data.VesselDetail.push(vesselDetail);
const json = JSON.stringify({mainModel: data});
console.log(json);
As you can see, VesselName is not blank.
try this, it was tested in VS2019 and working properly
var mainModel= { VesselDetail : { VesselName :"XYZ"} };
$.ajax({
url: '/Controller/PostUserData',
type: 'POST',
data: { mainModel: mainModel),
success: function (result) {
hideSpinner();
alert(JSON.stringify(result));
},
error: function (request) {
hideSpinner();
}
});
and fix VesselDetail class by adding setter and getter
public class VesselDetail
{
public string VesselName { get; set;}
}
And I see a bug in your action. What is a Data?
return new JsonResult { Data = "OK" };
try this
return new JsonResult(mainModel.VesselDetail.VesselName);
but if you like it a hard way you can try this
class VesselDetail {
VesselName;
}
class MainModel {
VesselDetail = {};
}
let mainModel= new MainModel();
data.VesselDetail.VesselName="XYZ";
UPDATE
Sometimes this working better, depending on net version or if you are using API controller
var mainModel= { VesselDetail : { VesselName :"XYZ"} };
$.ajax({
url: '/Controller/PostUserData',
type: 'POST',
data: JSON.stringify(mainModel),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
hideSpinner();
alert(JSON.stringify(result));
},
error: function (request) {
hideSpinner();
}
});
but you have to add [FromBody] to action
[HttpPost]
public JsonResult PostUserData([FromBody] MainModel mainModel)
{
return new JsonResult(mainModel.VesselDetail.VesselName);
}
you put the VesselName out of the builder
should be like this
class VesselDetail {
constructor() {
this.VesselName;
}
}
class MainModel {
constructor() {
this.VesselDetail = [];
}
}

ASP.NET: Ajax doesn't send string

I have this method to send some data with ajax:
function SendData(foodID, basketID) {
var data = { FoodID: foodID, BasketID: basketID };
$.ajax({
url: '/Order/Post',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json;utf-8',
datatype: 'json'
}).done(function (data) {
console.log(data);
}).fail(function (data) {
console.log("Error: " + data);
});
}
In C#, my Post Method in my Order controller gets triggered, but the string I want to hand over is null:
public bool Post(string s)
{
//When this gets executed, s is null
return true;
}
I tested this by executing SendData(1,1) directly on a button click. What is the mistake I'm doing and how can I get the string in my Post-Method?
you are post the object. not string.
you can try generate to object and load this object. or add new one parameter to action (foodId and basketId but you must post like that if you check this option data:{foodId,basketId})
//model
public class SomeObject{
public string FoodId {get;set;}
public string BasketId {get;set;}
}
//code
public bool Post(SomeObject data)
{
return true;
}
It seems for me your data structure to the Post action doesn't match action parameter names. Try this:
[HttpPost]
public bool Post(string foodID, string baskedID)
{
return true;
}
I believe you have to name your data that's being passed like so:
data: { 's': JSON.stringify(data) }

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.

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),

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

Categories

Resources