I'm developing an ASP.NET MVC 5 application with C#, .NET Framework 4.7 and jQuery 1.11.2.
This javascript code:
function RequestCodes(button, poId) {
var URL = '/ProductionOrder/RequestCodeForIncompleteOrder';
//button.attr("disabled", "disabled");
$('#ok').hide();
$('#fail').hide();
$('#cargando').show();
$.ajax({
url: URL,
type: "PUT",
dataType: "HTML",
data: { productionOrderId: poId },
contentType: "json",
success: function () {
$('#cargando').hide();
$('#ok').show();
$("#ok").fadeOut("slow", function () {
$('#ok').hide();
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
$('#cargando').hide();
$('#fail').show();
$("#fail").fadeOut("slow", function () {
$('#fail').hide();
//button.removeAttr("disabled");
});
}
});
}
Throws this error:
he parameters dictionary contains a null entry for parameter
'productionOrderId' of non-nullable type 'System.Int32' for method
'System.Web.Mvc.ActionResult RequestCodeForIncompleteOrder(Int32)' in
'TRZF.Web.API.Controllers.ProductionOrderController'. An optional
parameter must be a reference type, a nullable type, or be declared as
an optional parameter.Parameter name: parameters.
When I call the method:
public ActionResult RequestCodeForIncompleteOrder(int productionOrderId)
The problem is with the parameter name in the javascript code, but I don't know how why because it has the same name like in the C# code.
How can I fix this error?
Here is the solution:
you have syntax error at below line. I have fixed this.
data: "{'productionOrderId':'" + poId + "'}",
I have found the problem.
$.ajax({
url: URL,
type: "PUT",
data: { productionOrderId: poId },
success: function () {
$('#cargando').hide();
$('#ok').show();
$("#ok").fadeOut("slow", function () {
$('#ok').hide();
});
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
$('#cargando').hide();
$('#fail').show();
$("#fail").fadeOut("slow", function () {
$('#fail').hide();
//button.removeAttr("disabled");
});
}
});
I have removed dataType: "HTML", and contentType: "json",, and now it works.
I have done another test, removing only contentType: "json", and it works. So, I think the problem is with setting the contentType.
at controller RequestCodeForIncompleteOrder function you need to get productionOrderId with nullable data type like following :
RequestCodeForIncompleteOrder(int? productionOrderId)
{
//your code here
}
? mean accept nullable data type
changing the content type to "application/json" and strigifying the data fixed the issue for me.
here is the sample code.
$.ajax({
url: "/Home/RequestCodeForIncompleteOrder",
type: "POST",
dataType: "json",
data: JSON.stringify({
productionOrderId: 1
}),
contentType: "application/json",//change "json" to "application/json"
success: function () {
console.log("success");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
First of, is your route to the api correct?
Usually it's prefixed with api/..
Secondly, the client model that you are sending to the server is not matching the expected value type (int) on the server side.
Option 1 is to match the server side with the client side object.
Your client object { productionOrderId: poId } is equal to a server side model defined as this
public class RequestModel
{
public int productionOrderId { get; set; }
}
Use the model in the api controller method and read it from the body
public ActionResult RequestCodeForIncompleteOrder([FromBody]RequestModel model){}
NOTE: Don't forget to stringify the object before sending it in the client when using content type application/json, data: JSON.stringify({ productionOrderId: })
Option 2 is to send the productionOrderId in the route
[RoutePrefix("api/ProductionOrder")]
public class ProductionOrder : ApiController
{
[HttpPut]
[Route("RequestCodeForIncompleteOrder/{productionOrderId}")]
public ActionResult RequestCodeForIncompleteOrder(int productionOrderId){}
}
Then call this method by using url api/ProductionOrder/RequestCodeForIncompleteOrder/2345 where 2345 is your order id
Related
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.
I've tries setting breakpoints at the Controller method. But it does not stop there. The alerts "clicked" and the next one work perfectly fine. But the controller method is not called. Any help is appreciated. Here's my ajax call and my controller method.
var Url = "#Url.Action("~/Home/Get_Location")";
$("#gotoloc").click(function() {
alert("clicked");
alert(lat +" "+ lon);
$.ajax({
type: "POST",
url: Url,
data: {
latitude: lat,
longitude: lon
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Hello:" + response)
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
alert("ignored");
});
public JsonResult Get_Location(double latitude,double longitude)
{
string loc = latitude + "/" + longitude;
return Json(loc, JsonRequestBehavior.AllowGet);
}
You are using the Url.Action method incorrectly.
Try this
var Url = "#Url.Action("Get_Location","Home")";
The above overload takes the action method name as first parameter and controller names as second parameter
Also, i see you are passing incorrect contentType request header. contentType headers tells the server what is the type of data the client is sending. Your current code says you are sending json data. But you have 2 parameters in your action method and the json serializer will fail to properly map the posted data to it, hence you will be getting a 500 response from the server.
This should work, assuming there are no other js errors in your page
var url = "#Url.Action("Get_Location","Home")";
$.ajax({
type: "POST",
url: url,
data: { latitude: 44, longitude: 55 },
success: function (response) {
console.log("Hello:" + response);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
This question already has answers here:
Send JSON data via POST (ajax) and receive json response from Controller (MVC)
(8 answers)
Closed 9 years ago.
I have a text box and a button next to it. I want to send the content of textbox through Jquery ajax call to webmethod and get back the upper case value of the same and display that in alert. So far i have this code but its not working.
JAVASCRIPT:
function CallWM()
{
var name = $('#name').val();
RealCallWM(name);
}
function RealCallWM(name) {
$.ajax({
url: 'Register.aspx/UpperWM',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { name: JSON.stringify(name) },
success: OnSuccess(response),
error: function (response) {
alert(response.responseText);
}
})
};
HTML:
Name: <input id="name" type="text" />
<input id="Button1" type="button" value="button" onclick="CallWM();"/></div>
</form>
WEB METHOD:
[WebMethod]
public static string UpperWM(string name )
{
var msg=name.ToUpper();
return (msg);
}
Replace:
data: '{name: ' + name + '}',
with:
data: { name: JSON.stringify(name) },
to ensure proper encoding. Right now you are sending the following payload:
{name:'some value'}
which is obviously an invalid JSON payload. In JSON everything should be double quoted:
{"name":"some value"}
That's the reason why you should absolutely never be building JSON manually with some string concatenations but using the built-in methods for that (JSON.stringify).
Side note: I am not sure that there's a callback called failure that the $.ajax method understands. So:
$.ajax({
url: 'Register.aspx/UpperWM',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { name: JSON.stringify(name) },
success: OnSuccess(response),
error: function (response) {
alert(response.responseText);
}
});
Also notice that in your error callback I have removed the response.d property as if there's an exception in your web method chances are that the server won't return any JSON at all.
As per your comment I understood your issue not yet resolved, so just try this
function RealCallWM(name) {
$.ajax({
type: "POST",
url: "Default.aspx/UpperWM",
data: JSON.stringify({ name: $('#name').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
console.log("CallWM");
alert(data.d);
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
}
});
}
I have the following request:
var response = $.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: this.AgentServiceUrl + "/" + methodName,
data: data,
async: this.Async,
success: function (xml, textStatus) { if (successHandler != null) successHandler(state, $.xml2json(xml), textStatus); },
error: function (xmlHttpRequest, textStatus, errorThrown) { if (errorHandler != null) errorHandler(state, xmlHttpRequest, textStatus, errorThrown); }
});
I want to add to a variable to this request header and consume it on C#,
I try many ways but I can't consume it on C#:
beforeSend: function (req)
{
req.setRequestHeader("AgentGUID", this.AgentGUID);
},
Pass parameters:
Can you help me? I don't want to change the function at the C# part I just want to use something like:
(System.Web.HttpContext.Current.Request.Headers["someHeader"]
Your beforeSend should work as you wish, but the reason you are not getting the value on server side is that this.AgentGUID on this method call is undefined because this in that context is pointing to another object (most probably ajax request object).
By defining a variable outside your ajax call you issue will be fixed.
var me = this;
var response = $.ajax({
...
beforeSend: function (req)
{
req.setRequestHeader("AgentGUID", me.AgentGUID);
},
...
});
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.