Passing two parameters to another controller with js - javascript

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

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

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 = [];
}
}

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.

How to get data from json in lightgallery jquery?

I face with a problem in use lightgallery with jquery .When I use constant value for src and thumb it works great, but in the opposite it doesn't work with json . I see this kind of error in firebug.
Error
-data-src is not provided on slide item
HTML Code
<a id="dynamic" href>Open lightGallery</a>
$('#dynamic').on('click', function(e) {
var arr='';
$.ajax({
type: 'post',
url: "#Url.Action("ShowMenuGallery", "Ads")",
contentType: 'application/json; charset=utf-8',
data: '{"ID":"' + #Model.ID + '"}',
traditional: true,
success: function (data) {
arr=data;
console.log(arr);
}
});
$('#dynamic').lightGallery({
dynamic: true,
html:true,
dynamicEl: JSON.stringify(arr)
})
});
Controller.cs
public ActionResult ShowMenuGallery(int id)
{
ViewBag.guid = Guid.NewGuid();
List<string> menuImage = new List<string>();
ReturnImages(((Guid)ViewBag.guid).ToString(), id, ref menuImage);
List<MyClass> data = new List<MyClass>() { new MyClass() { src =menuImage[0] , thumb = menuImage[0] } };
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
operations = data
});
return Json(json);
}
public class MyClass
{
public string src { get; set; }
public string thumb { get; set; }
}
Try once this code
jQuery(document).ready(function($) {
$("#dynamic").on("click", function(e) {
$.ajax({
type: "post",
url: "#Url.Action("ShowMenuGallery", "Ads")",
dataType: "json",
data: {ID: "#Model.ID"},
traditional: true,
success: function (data) {
$("#dynamic").lightGallery({
dynamic: true,
html:true,
dynamicEl: JSON.stringify(data)
});
}
});
});
});
For more information see https://boxoverflow.com/get-json-jquery-ajax/

sending data from js over wire to the controller

Inside js function I'm creating javascript object which I then send to the mvc controller using ajax
var ab = { id: 100, name: "abc" }
$.ajax({
type: "POST",
url: "/home/dosomething",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(ab),
success: function (result) {
$("#myDiv").html(result);
$("#showModal").modal("show");
},
error: function () {
alert("error!");
}
});
on server side I have
[HttpPost]
public ActionResult DoSomething(string ab)
{
... ab is always null
}
I'm guessing that I should using some other data type as expected in controller method instead of string?
You need to use id and name in your action method
[HttpPost]
public ActionResult DoSomething(int id, string name)
{
//code
}
Try this:
JS:
var ab = { Id: 100, Name: "abc" }
$.ajax({
type: "POST",
url: "/home/dosomething",
dataType: "json",
data: JSON.stringify({ ab: ab }),
success: function (result) {
$("#myDiv").html(result);
$("#showModal").modal("show");
},
error: function () {
alert("error!");
}
});
Controller:
[HttpPost]
public ActionResult DoSomething(YourClass ab)
{
. . .
}
Model:
public class YourClass
{
public int Id { get; set; }
public string Name { get; set; }
}
Make a class of the JSON object, peg it as Serializable
[Serializable]
public class SomeClass
{
public int id { get; set; }
public string name { get; set; }
}
In your controller, you can now accept this as:
[HttpPost]
public ActionResult DoSomething([FromBody] SomeClass someclass){
// code
}
var ab = { id: 100, name: "abc" }
$.ajax({
type: "POST",
url: "/home/dosomething",
dataType: "json",
contentType: "application/json",
// what if you pass data like this
data: JSON.stringify({ab:ab}),
success: function (result) {
$("#myDiv").html(result);
$("#showModal").modal("show");
},
error: function () {
alert("error!");
}
});
If you want to send { id: 100, name: "abc" } as a string to the controller you need to change the data in ajax call to
data: JSON.stringify({ab:ab}),
if you want to send id and name as separate paramamters change your controller to
public ActionResult DoSomething(string id, string name)
{
}
and your ajax call data to
data: '{ "id":" 100 ","name":"abc" }',

Categories

Resources