Pass array to Controller Action via AJAX - c#

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,

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.

Map Json data to an object using AJAX and C#

how can I use the Json formatted data sent by an AJAX request in C#?
Here's the View with the JQuery and AJAX
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
var values =
{
"Name": "Manuel Andrade",
"DateOfBirth": "12/01/1995"
}
$.ajax({
type: "POST",
url: "/api/WebApi/GetAge",
data: values,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
</script>
Here's the Controller:
public class PersonController : ApiController
{
[System.Web.Http.Route("api/WebApi/GetAge")]
[System.Web.Http.HttpPost]
public Person GetAge(Person person)
{
//person = new Person();
//person.Name = "Luis";
JsonTest(person);
//int ageInMonths = calculateAgeInMonths(person);
//int ageInYears = calculateAgeInYears(person);
//System.Diagnostics.Debug.WriteLine(ageInMonths);
//System.Diagnostics.Debug.WriteLine(ageInYears);
return person;
}
}
The Person Model has exactly the same attributes as the Json variable in the view. Shouldn't it create an object automatically? The method JsonTest() works properly, it is used to serialize the data. If I uncomment the person instantiation and assignation to Luis the method does return a Json with that data to the view. But if I try to use the person parameter just like that it throws a null Exception. How can I pass the var values in the View to the GetAge method so I can assign it to an object?
It worked fine for me when I removed the contentType: "application/json; charset=utf-8", line.
It isn't returned as application/json by default.

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.

json Array posting to mvc controller

I want to post JSON array to MVC controller through AJAX POST as:
$.ajax({
type: 'POST',
data: json.stringify(totaldata),
traditional:true,
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
and my controller code is have made array of one ViewModel & want to update those values as.
[HttpPost]
public ActionResult Save(IList<ItemEditViewModel> data,long playlistid=0, string Title="")
{
for (int i = 0; i < data.Count; i++)
{
var pc = db.PlaylistContents.FirstOrDefault(x => x.PlaylistContentId == data[i].ID);
if (pc == null)
{
pc = new PlaylistContent();
db.PlaylistContents.Add(pc);
}
pc.ContentMetaDataId = data[i].MetaID;
pc.PlaylistContentSequenceId = i + 1;
}
db.SaveChanges();
return RedirectToAction("Playlist", new {ID=playlistid });
}
But the Object is set to null in Controller.
My ViewModel is as,
public class ItemViewModel
{
public long ID{get;set;}
public long MetaID{get;set;}
}
Try adding the content type in ajax call,
contentType : 'application/json',
By default ajax sends with content type application/x-www-form-urlencoded; charset=UTF-8
Edit
also i dont know it this is a typo, json.stringify should be JSON.stringify
hope this helps.
$.ajax({
type: 'POST',
data: {"data":json.stringify(totaldata)},//You missed the format
traditional:true,
url: '/Builder/Save',
success: function () {
alert("Playlist saved successfully!!");
}
})
The Problem is solved & my application is working now properly.
I have just done JSON.stringify() on array elements & not the whole ajax data for posting.
the code is as written below:
var totaldata = { data: data, playlistid: parseInt(playlistid), Title: Title };
$.ajax({
type: 'POST',
data: { data: JSON.stringify(data), playlistid: parseInt(playlistid), Title: Title, deleted: JSON.stringify(deleted) },
traditional:true,
url: 'Save',
success: function (data) {
alert("Playlist saved successfully!!");
}
})

Categories