ASP.NET MVC JSON get value with two Parameters - c#

I am trying to get value based on 2 parameters, below is my function where I added my 2 parameters in JSON stringify :
function GetItemLocationOnHand(itemId, locationId) {
var data = JSON.stringify({
itemId: itemId,
locationId: locationId
});
$.ajax({
async: true,
type: 'GET',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: data,
url: 'getItemInventory3',
success: function (data) {
$("#txtInventory3").val(parseFloat(data).toFixed(2));
},
error: function () {
alert("Error")
}
});
}
Below is my code in my controller to retrieve the data I want based on these two parameters :
[HttpGet]
public JsonResult GetItemLocationOnHand(int itemId, int locationId)
{
var itemLocQuantity = objDB.ItemLocationDatas.Single(items => items.ItemId == itemId && items.LocationId == locationId).Quantity;
return Json(itemLocQuantity, JsonRequestBehavior.AllowGet);
}
Upon calling this function via below on change code, I can't seem to get my data and is always returning the error.. If I only have 1 parameter, then no error encountered.
Please advise what went wrong when trying to pass 2 parameters.
$("#LocationId").change(function () {
var itemId = $("#ItemId").val();
var locationId = $("#LocationId").val();
GetItemLocationOnHand(itemId, locationId)
});

Issue solved by doing the following :
added correct URL which is GetItemLocationOnHand
removed Stringify and used var data = ({ itemId: itemId, locationId:
locationId });
thanks a lot to Freedom and Reflective and others for your comments!
function GetItemLocationOnHand(itemId, locationId) {
var data = ({ itemId: itemId, locationId: locationId });
$.ajax({
async: true,
type: 'GET',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: data,
url: 'getItemLocationOnHand',
success: function (data) {
$("#txtInventory3").val(parseFloat(data).toFixed(2));
},
error: function () {
alert("Error")
}
});
}

Just to avoid some misunderstanding how AJAX GET works and setting some parameters which you don't have to set (i.e. you are still not so deep into jQuery AJAX) you may use the shortcut they also implemented i.e. $.get so your request will look as simple as that and you can't get wrong as it will use the proper defaults for GET. If you want the response to be treated as JSON, just set Content-type of your response headers (from backed) to application/json. This will be checked by jQuery AJAX response handler and it will parse the incoming data as JSON.
var data = {itemId: 1, locationId: 2 };
$.get('GetItemLocationOnHand', data, function (data) {
$("#txtInventory3").val(parseFloat(data).toFixed(2));
}).fail(function (jqXHR, textStatus ) {
alert(`Error = ${jqXHR.status} ${textStatus}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

See my example below. This works for me when doing ajax requests to a MVC controller with multiple params.
Below is my MVC controller action with multiple params.
// GET
[HttpGet]
public ActionResult Index(string referenceID, int typeID, int supplierID, bool isArchived)
{
// Do CODE here
}
Below is my Ajax request that I use to get or post. Depending on your needs. I use data type 'JSON' and format my data as a JSON object.
var formData = {referenceID: 'Test', typeID: 3, supplierID: 2, isArchived: false};
$.ajax({
type: 'GET',
cache: false,
url: getActionUrl, // url: domain/controller/action |or| domain/area/controller/action
dataType: 'json',
contentType: 'application/json; charset=utf-8',
headers: headers, // ignore if not needed. I use it for __RequestVerificationToken
data: formData,
success: function (data, status, xml) {
// do something with the data
},
error: function (xml, status, error) {
console.log(xml)
// do something if there was an error
},
complete: function (xml, status) {
}
});
I think your issue might be that you are using 'JSON.stringify'. It could be interpreting your JSON string as a single parameter input and not two separate parameters.
Please see below snippets from documentation. https://api.jquery.com/jquery.ajax/
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.

Related

Trouble sending JSON data to another action in asp.net MVC controller

I have this controller action:
[HttpPost]
public ActionResult OrderData(Order order)
{
var result = new { redirectToUrl = Url.Action("SeatSelection", "Orders", new { id = order.ScreeningId }), order };
return Json(result);
}
and I'm trying to pass the order object to another action:
public ActionResult SeatSelection(int id, Order order)
{
var screeningInDb = _context.Screenings.Include(s => s.Seats).Single(s => s.Id == order.ScreeningId);
var viewModel = new SeatSelectionViewModel
{
Seats = screeningInDb.Seats,
NumberOfTicketsOrdered = order.NumberOfTicketsOrdered
};
return View("SeatSelection", viewModel);
}
The problem is - the only parameter I'm receiving in SeatSelection Action is the id parameter, although the order object in OrderData Action is valid. I'm pretty sure the problem is within the way I'm trying to pass the order object, maybe something with the syntax?
Here is the way I'm posting my form data to the OrderData Action:
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(orderData),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
Bottom line - What I'm eventually trying to do is to pass the form to a Controller Action where the data will be processed, and then pass the new data to "SeatSelection" view. I had trouble doing this as my post method sends JSON data, so if there is a better way to do what I'm trying to do, I would be happy to learn!
Your model doesn't match SeatSelection parameter signature.
Try:
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: `{"order": ${JSON.stringify(orderData)}}`,
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
or (this one just creates a javascript object, which has the two signature properties in):
const sendObj = { id: 0, order: orderData };
$.ajax({
type: "POST",
url: '#Url.Action("OrderData", "Orders")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(sendObj),
dataType: "json",
success: function (res) {
alert("Success!");
window.location.href = res.redirectToUrl;
},
error: function (xhr, status, error) {
alert(status);
}
});
you can't use
window.location.href = ...
because in this case browser always calls a GET method that can only keep data in a query string with primitives parameters and it doesn't convert Order to a qusery string parameters. This is why you can get only id.
in your case it would be much easier to redirect directly in the action
public ActionResult OrderData(Order order)
{
return RedirectToAction( ( "SeatSelection", "Orders", new { id = order.ScreeningId }), order });
}
or when it is the same controller I usually do this
public ActionResult OrderData(Order order)
{
return SeatSelection (order.ScreeningId, order };
}
but since you are using ajax it will redirect, but will not update your view. For ajax you need a partial view that should be updated on success. So instead of ajax you can only submit form using button. In this case everything will be working ok.
Another way you can use ajax is you can try to split the order in properties and create a query string.

ajax post data is null in controller asp.net mvc 5

I try to send a JSON object back to the server. This is my AJAX call
function SaveData() {
var model = []
debugger
$.each($('.Money'), function (i, item) {
model.push({
Money: $('.Money').eq(i).val(),
Day: $('.Day').eq(i).val(),
Note: $('.Note').eq(i).val()
});
})
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: { partnerDeposit: JSON.stringify(model) },
type: 'POST',
dataType: 'json',
succsess: function () {
}
})}
This is the method in the controller which is being called:
enter image description here
https://i.stack.imgur.com/FqEt9.png
The problem I have is that always the json variable from above is an empty object. The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong. Thank you.
Try adding the partnerDeposit to the JSON.stringify call like this:
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: JSON.stringify({partnerDeposit: model}),
type: 'POST',
dataType: 'json',
succsess: function () {
}
})
I haven't found this answer anywhere else so I had to discover it through experimentation. Hopefully this will help someone.
You'll find that in your controller, it's receiving a Request.Form object and if you look in Request.Form[0] you'll find your data. The reason that there's data in the form but MVC is seeing it as null is that the key to the form element being POSTed is "" (blank).
So client side, you have to set content type properly, and precede your data with something like "myData=" + JSON.stringify(myJSONObject), where "myData" is the key name you are adding, like so:
$.ajax({
type: "POST",
url: URL,
data: "myData="+JSON.stringify(myJSONObject),
contentType: "application/x-www-form-urlencoded; charset=utf-8"
On the server side, your [HttpPost] endpoint has to have as its input a variable with the same name as the key you declared in your AJAX, like so:
`
[HttpPost]
[Authorize]
public ActionResult Index (string myData) // <-- var name matches AJAX
{
// de-serialize data into server-side object using
// JSONConvert.DeserializeObject
}
`

Asp.net MVC 5 Modelbinding multiple JSON objects (knockoutjs)

Ok. I've encountered a problem that i just can't understand.
First of all, i'm trying to post several ko.observableArrays to the controller as JSON and modelbinding them seperately. When i post only one and don't name it in the data attribute of .ajax it posts just fine and modelbinds flawlessly.
This is my a snippet from my viewModel and is how i am attempting to post the two JSON objects.
self.timeRanges = ko.observableArray();
self.geoRequirements = ko.observableArray();
self.saveWorkWish = function() {
$.ajax({
url: "#Url.Action("SaveWorkWish")",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: {
timeRanges: ko.toJSON(self.timeRanges()),
geoRequirements: ko.toJSON(self.geoRequirements())
},
complete: function (data) {
console.log(data);
}
});
};
My Action
public JsonResult SaveWorkWish(IList<JSONTimeRanges> timeRanges, IList<JSONGeoRequirements> geoRequirements)
{
// do stuff
}
I get this exception:
Invalid JSON primitive: timeRanges.
Interesting to note is that, when i do:
$.ajax({
url: "#Url.Action("SaveWorkWish")",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.timeRanges()),
complete: function (data) {
console.log(data);
}
});
And
public JsonResult SaveWorkWish(IList<JSONTimeRanges> timeRanges)
{
// do stuff
}
It works just fine.
Lastly a thing that i noticed, and is likely the cause of the error is that:
When i post 2 Jsons like in the example,
this is what chrome tells me i post:
timeRanges=%5B%7B%22startDate%22%3A%2214-09-2014%22%2C%22endDate%22%3A%2220-09-2014%22%2C.....etc..
and in the working example:
it is a well formated and readable JSON object.
So it seems like the error is indeed correct and that i am not sending valid JSON to the controller.
But..what am i doing wrong?
Try to convert observables to JSON first and then convert the whole object to json string:
data: JSON.stringify({
timeRanges: ko.toJS(self.timeRanges()),
geoRequirements: ko.toJS(self.geoRequirements())
}),

JSON and other parameters in data property of AJAX PUT. ASP.net Web API

I want to send a JSON object and values from text boxes back to my controller, but I am having trouble. I can send just the JSON object successfully, but as soon as I add other parameters I get an error saying the requested resource does not support http method 'PUT'. I have tried commenting out the contentType and using Data: {viewModel: JSON.stringify(jsonData), userName: username}, without any success (I eventually will add more string parameters). Below is my ajax and controller signature. Thanks in advance.
$.ajax({
type: 'PUT',
contentType: 'application/json',
url: 'api/Label',
cache: false,
data: JSON.stringify(jsonData),
success: function (result) {
// TODO
},
error: function (HttpRequest, textStatus, err) {
var response = jQuery.parseJSON(HttpRequest.responseText);
$('#LabelInfo').show();
$('#LabelInfo').text('Error: ' + response.ModelState["viewModel.Pieces"][0]);
}
});
controller signature:
public HttpResponseMessage Put(Label viewModel, string
userName)

MVC3 Controller not receiving any parameter values

Using JQuery, I am passing values to an action in the controller. customerId and productId are not null:
$.ajax({
type: "GET",
url: "Customer/Product/",
data: { Customer: customerID, Product: productId},
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
$("#productName").innerHTML = json;
alert(json);
alert($("#startDate").innerHTML);
}
});
In MVC3 controller, i have the action:
public ActionResult Product(string Customer, string Product)
{
//both are null
}
I don't know why both are null? Please guide
$.ajax({
type: "GET",
url: "Customer/Product/",
data: "Customer="+customerID +"&Product="+productId,
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
$("#productName").innerHTML = json;
alert(json);
alert($("#startDate").innerHTML);
}
});
Try this way.
MVC may be expecting a JSON string. Try using this as your data
data: JSON.stringify({ Customer: customerID, Product: productId})
If you change it to a "POST" request it should work.
However it looks like you are actually trying to just "GET" data from the server which should really be encoded in your URL e.g. mysite.com/Customer/{customer_id}/Product/{product_id}. In this case you'll probably need to change your routing rules.
I just did "File -> New Project" and just added the one controller and tried directly using:
var customerID = 42;
var productId = 4242;
$.ajax({
type: "GET",
url: "http://localhost:51622/Customer/Product",
data: { Customer: customerID, Product: productId},
dataType: "json",
error: function (xhr, status, error) {
// you may need to handle me if the json is invalid
// this is the ajax object
},
success: function (json) {
console.log(json);
}
});
It binds the values just fine, so you might want to grab fiddler or something similiar and make sure that you are actually sending values to the server.

Categories