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

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.

Related

ajax request to razor page using handler

I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});

Pass array to Controller Action via AJAX

I saw similar questions, but none helps me.
I have the simplest code:
public JsonResult JsonGetStatesInfo(object[] instructions)
{
if (Request.IsAjaxRequest())
{
return Json(String.Empty);
}
else
throw new NoAjaxRequestException();
}
and client side:
var instructions = [];
instructions.push('abc');
instructions.push('ddd');
instructions.push('assdbc');
var inst = JSON.stringify(instructions);
$.ajax({
cache: false,
data: { 'instructions': inst },
traditional: true,
dataType: 'json',
url: '/State/JsonGetStatesInfo',
type: 'post',
success: function (resp) {
},
error: function (data) {
alert(data.error);
}
});
On client side I tried with JSON.stringify, without JSON.stringify, with traditional: true, without traditional: true
On server side I tried as parameter : object[], object, List< object >, List< string >, IEnumerable< string > etc
Nothing worked! How to do it correctly?
SOLVED:
My problem was trivial - one from real values of array had HTML Tag. Just need add [ValidateInput(false)] to action method
You just need the following settings:
Pass array of string to a MVC Action by Ajax:
Controller:
public JsonResult MyAction(string[] instructions)
{
// Your codes
}
View:
$.ajax({
data: { 'instructions': ['abc', 'dcs', 'arr'] }, // << Without JSON.stringify
traditional: true, // << Important line
url: '/State/MyAction',
type: 'post',
dataType: 'json',
success: function (resp) {
// Your codes
}
});
Using contentType: "application/json; charset=utf-8" is recommended too.
Pass array of int to a MVC Action by Ajax:
Also I use bellow codes to path an array of int to an Action
Controller:
public JsonResult MyAction(int[] instructions)
{
// Your codes
}
View:
$.ajax({
data: { 'instructions': [1, 2, 3] }, // << Without JSON.stringify
traditional: true, // << Important line
url: '/State/MyAction',
type: 'get',
dataType: 'json',
success: function (resp) {
// Your codes
}
});
public ActionResult JsonGetStatesInfo(string[] instructions)
{
return new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { result = instructions.Length}
};
}
Client side
var instructions = ['abc', 'dcs', 'arr'];
$.post('/State/JsonGetStatesInfo', { instructions: instructions },
function (data) {
if (data.result!= null && data.result!= undefined) {
alert(data.result);
}
});
Try this...
At least, you can pass javascript array as a string and deserialize it in the controller
public JsonResult JsonGetStatesInfo(string instructions)
var instructionsArray= JsonConvert.DeserializeObject<string[]>(instructions);
Or use new Array like explained here : https://stackoverflow.com/a/310136/3063094
Try adding:
contentType: "application/json; charset=utf-8"
To you AJAX call, And please delete the:
JSON.stringify(instructions);
Because you are trying to stringify an object, which will be sent to the server as a string rather than an object (and the server side expects an object).
you can also delete the
traditional: true,
ache: false,

Pass Strongly Typed data and JSON string to controller from $.ajax funtion in View

I have ASP.NET-MVC5 application. I have strongly typed form and I successfully can pass back to controller. Now I have JavaScript array variable that I need to also send so I need to post back both information from view to controller using .$ajax post function.
I have update code as to add avaScript array variable, since then I am getting null value for form data.
View
var AdditionalTenentList = {
StudentUWLID: []
};
$('#CreateStudentRentingApplicationForm').submit(function (e) {
e.preventDefault();
var AdditionalTenentJsonList = JSON.stringify(AdditionalTenentList);
alert(AdditionalTenentJsonList);
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: { ApplicationModelData: $(this).serialize(), TenentJSONList: AdditionalTenentJsonList },
}).done(function (data, textStatus, jqXHR) {
//// my other code here.....
}
</script>
In another function thats how I am pushing value to array
AdditionalTenentList.StudentUWLID.push(StudentUWLID);
Controller
[Authorize]
[HttpPost]
public ActionResult ApplyForAccommodation(AccommodationApplicationViewModel ApplicationModelData, string TenentJSONList)
{
return null;
}
with the following code I get header response as
$.ajax({
url: formURL,
type: "POST",
dataType:"JSON",
data: JSON.stringify({ TenentJSONList: AdditionalTenentList }),
}).done(function (data, textStatus, jqXHR) {
..........
public ActionResult ApplyForAccommodation(string [] TenentJSONList)
{
var a = "d";
return null;
}
I have found the answer as following;
var AdditionalTenentList = new Array();
$('#CreateStudentRentingApplicationForm').submit(function (e) {
e.preventDefault();
var formURL = $(this).attr("action");
var formData = $(this).serialize();
$.ajax({
url: formURL,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ TenentJSONList: AdditionalTenentList, ApplicationModelData: $("#CreateStudentRentingApplicationForm").serializeObject() }),
}).done(function (data, textStatus, jqXHR) {
// .........my rest of code
...
[Authorize]
[HttpPost]
public ActionResult ApplyForAccommodation(string[] TenentJSONList, AccommodationApplicationViewModel ApplicationModelData)
{

Object obect error on jquery ajax request on dropdown change?

I'm using jquery ajax on dropdown change function.The problem is that even before hitting the url mentioned in the ajax request I'm getting Object object error.
The ajax request is as follows
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: "{ 'Location': '" + locationNo + "'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
The server side code is as follows
[WebMethod]
public static string GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
System.Web.Script.Serialization.JavaScriptSerializer jSearializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sjson=jSearializer.Serialize(lstCashSafeSelect);
return sjson;
}
I've checked the string sjson and the data is returning correctly in json format.
Since the error is showing even before the url is hit,i'm confused on how to proceed further.
Any help will be appreciated.
Change the data like this
data: JSON.stringify({ 'Location': locationNo }),
Then your code will look like
$("#locationList").change(function () {
var locationNo = document.getElementById('<%=locationList.ClientID%>').value;
$.ajax({
url: "HealthReport.aspx/GetCashsafes",
data: JSON.stringify({ 'Location': locationNo }),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success");
response($.each(data.d, function (key, value) {
$("#CashSafeList").append($("<option></option>").val(value.CashsafeId).html(value.CashsafeDisplaySerialNo));
}));
},
error: function (result) {
alert(result);
$("#CashSafeList").append($("<option></option>").val("-1").html("Select one"));
}
});
});
Edit
Since your dataType is json, you should return json, not string. Change your server side code like this,
[WebMethod]
public static List<CashSafeSelect> GetCashsafes(string Location)
{
Decimal userId = (Decimal)AMSECSessionData.userId;
List<Cashsafe> lstCashSafe = DropDown.getCashSafeListLocationwise(userId, Convert.ToDecimal(Location));
List<CashSafeSelect> lstCashSafeSelect = new List<CashSafeSelect>();
lstCashSafeSelect = lstCashSafe.Select(item => new CashSafeSelect()
{
CashsafeId=(decimal)item.CashsafeId,
CashsafeSerialNo=item.CashsafeSerialNo.ToString()
}).Distinct().ToList();
return lstCashSafeSelect;
}
You dont have to serialize those lists
Issue solved,Thanks to every one who replied especially #Anoop.
Issue was that I've set Autopostback=true for the dropdown where the ajax call is made.I've removed the autopostback property of the dropdown and now the code is working fine.
I wonder how a fresh day,clear mind helps to solve the issues.

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