How to ajax/post JSON array to ASP MVC - asp.net-mvc

Trying to do a post including some JSON data that has an array of integers in it. Pressing the button on my page to perform the post is getting to the action, but the expected data is not there (the two int[] variables are null). Doing a network profile while posting shows that the request body includes data like this:
groups%5B%5D=2&groups%5B%5D=3&alerts%5B%5D=5&alerts%5B%5D=9
Javascript:
$('#modal-save').click(function() {
var selectedGroups = [];
var selectedAlerts = [];
$('input:checked').filter('[data-group="true"]').each(function() {selectedGroups.push($(this).data('id')); });
$('input:checked').filter('[data-group="false"]').each(function() {selectedAlerts.push($(this).data('id')); });
$.ajax({
type:'Post',
dataType: 'json',
url:'#Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
data: {groups: selectedGroups, alerts: selectedAlerts},
});
MVC Action:
[HttpPost]
public bool UpdateAlertStores(string alias, Guid? groupID, Guid? storeID, int[] groups, int[] alerts)
{
return true;
}

add traditional:true
traditional: true,
type:'Post',
dataType: 'json',
url:'#Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
data: {groups: selectedGroups, alerts: selectedAlerts},
after this changing your url looks like:
groups=2&groups=3&alerts=5&alerts=9

Related

Controller in my MVC project returning null from Ajax Post call

I'm not sure to why the controller is receiving a data from an Ajax call . Could i be doing anything wrong?
[HttpPost]
[Route("Product/UpdateDetails")]
public ActionResult UpdateProduct (ProductModel model) <<// model here is null
{
Product p = new Product
{
ProductId = p.ProductId,
Price = p.Price,
};
return View("_ProductDetail"); }
Ajax call below:
var model = {
ProductId: 1,
Price: 270.99,
};
var json = JSON.stringify(model)
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
model: model,
success: function (results) {
}
});
//Model
public class Product
{
public int Id {get;set;}
public double Price {get;set;}
}
Can you guys spot anything that i may be doing wrong in the code above ? I can't see anything that i'm doing wrong.
Try this:
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
You used JSON.Stringify() on your model, but forgot to use the variable "json" on the ajax call, so the ajax was trying to post a "non-json" model.
Also, there is no model setting in ajax calls, the correct one to post your data is data, as you can see here.

Received parameter from ajax POST empty in controller + passed parameter in firebug MVC 4

I have looked over the net to figure out what my mistake is. All suggestions I found I tried, without any succes. I access the httppost action in my controller but the parameters stays empty.
AJAX function
var dataPost = { 'id': id, 'val': val };
debugger;
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: dataPost ,
contentType: 'json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
On debug DataPost is populated.
Controller
[HttpPost]
public ActionResult UpdateJson(string id, string val)
{
//do stuff
return Json(true);
}
The parameters I used in my controller have the same name as in my Ajax function. The format passed is json, I have also tried populating my data with:
var dataPost = { 'id': 'id', 'val': 'val' };
But this doesn't make any difference. I have also tried to work with a Class, like -->
Class
public class ScheduleData
{
public string id { get; set; }
public string val { get; set; }
}
Controller
public ActionResult UpdateJson(ScheduleData data)
{//Do something}
Any help would be appreciated. Thanks in advance
The format passed is json
No, not at all. You are not sending any JSON. What you do is
data: { 'id': id, 'val': val }
But as the documentation clearly explains this is using the $.param function which in turn uses application/x-www-form-urlencoded encoding.
So get rid of this contentType: 'json' property from your $.ajax call.
Or if you really wanna send JSON, then do so:
var dataPost = { 'id': id, 'val': val };
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: JSON.stringify(dataPost),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
Things to notice:
usage of JSON.stringify(dataPost) to ensure that you are sending a JSON string to the server
contentType: 'application/json' because that's the correct Content-Type value.

Post javascript module array as List object with ajax in asp .net mvc project

I want to send JavaScript object array as list object to server, the server side method(GetData) accepts list object with 3 elements, but all elements have null value. Any advice? Thanks in advance.
At Client:
User.js
define(function () {
function User(name) {
this.Name = name
}
return User;
});
main.js
var users = [new User('Barney'),
new User('Cartman'),
new User('Sheldon')];
$.ajax({
type: "POST",
url: "/Home/GetData",
data: {users: users},
success: function (data) {
//alert(data.Result);
},
dataType: "json"
});
At Server:
GetData action
public void GetData(List<User> users){
}
User Model
public class User {
public string Name { get; set; }
}
I changed main.js like below, and it worked:
main.js
var params = {'users': [new User('Barney'),
new User('Cartman'),
new User('Sheldon')]};
$.ajax({
type: "POST",
url: "/Home/GetData",
data: JSON.stringify(params),
success: function (data) {
//alert(data.Result);
},
contentType: "application/json"
});

mvc json request life cycle

I'm pretty new to asp.net and MVC.
I was trying to use json request and populate some text boxes.
but I noticed when I'm using json, I can not access values of the other text boxes in my view.
for example
string s2 = Request.Form["selectedTestCategory"];
would generate s2 = null, when I debug.
but if I put a submit button on the page, the value is not null. (And so far I know I can only pass one parameter to my JSON method in controller)
My question is what happens when I start a json request? and why I can not get a value from Request.Form[...]
Thanks,
Update:
This is my json
<script>
$(document).ready(function() {
$('select#testStationUniqueId').change(function() {
var testStation = $(this).val();
$.ajaxSetup({ cache: false });
$.ajax({
url: "TestInput/getTestStationInformation/" + testStation,
type: 'post',
success: function(data) {
$('#driveDetailDiv').empty();
for (var i = 0; i < data.length; i++) {
$.post('TestInput/Details/', { id: data[i] }, function(data2) {
$('#driveDetailDiv').append(data2);
});
}
}
});
});
});
And this is in my controller
public PartialViewResult Details(string id)
{
//DriveDetails t = new DriveDetails(id);
//return PartialView("DriveDetailsPartial", t);
test_instance_input_model ti = new test_instance_input_model();
string s2 = Request.Form["selectedTestCategory"];
repository.setTestInstanceAttributes(ti, id);
return PartialView("TestInstancePartial", ti);
}
the s2 is null in Details, but if I use a submit button, it will have the correct value.
so I'm trying to figure out why it is null when I send a json request.
In your JavaScript your not including any data in the jQuery ajax request (see jQuery ajax). Therefore jQuery isn't adding any request parameters. You need to include a data object which jQuery will turn into parameters i.e. the more properties in the data object the more parameters in the request.
$.ajax({
url: '',
data: { selectedTestCategory: 'category' },
dataType: 'post',
success: function() {}
});
Also, in your controller you can shortcut to the request parameter.
string s2 = Request["selectedTestCategory"];

Send list/array as parameter with jQuery getJson

I have the following where I'm trying to send list/array to MVC controller method:
var id = [];
var inStock = [];
$table.find('tbody>tr').each(function() {
id.push($(this).find('.id').text());
inStock.push($(this).find('.stocked').attr('checked'));
});
var params = {};
params.ids = id;
params.stocked = inStock;
$.getJSON('MyApp/UpdateStockList', params, function() {
alert('finished');
});
in my contoller:
public JsonResult UpdateStockList(int[] ids, bool[] stocked) { }
both paramaters are null.
Note that if I change the params to single items
params.ids = 1;
params.stocked = true;
public JsonResult UpdateStockList(int ids, bool stocked) { }
then it works ok, so I don't think it's a routing issue.
Try setting the traditional flag:
$.ajax({
url: '/home/UpdateStockList',
data: { ids: [1, 2, 3], stocked: [true, false] },
traditional: true,
success: function(result) {
alert(result.status);
}
});
works fine with:
public ActionResult UpdateStockList(int[] ids, bool[] stocked)
{
return Json(new { status = "OK" }, JsonRequestBehavior.AllowGet);
}
Besides calling .ajax() instead of .getJSON() as Darin suggests or setting the global jQuery.ajaxSettings.traditional to true as jrduncans suggests, you can also pass the result of calling the jQuery .param() function on your params object:
var id = [];
var inStock = [];
$table.find('tbody>tr').each(function() {
id.push($(this).find('.id').text());
inStock.push($(this).find('.stocked').attr('checked'));
});
var params = {};
params.ids = id;
params.stocked = inStock;
$.getJSON('MyApp/UpdateStockList', $.param(params, true), function() {
alert('finished');
});
Unfortunately, while it seems that jquery provides a "traditional" flag to toggle this behavior on jQuery.ajax, it does not on jQuery.getJSON. One way to get around this would to be set the flag globally:
jQuery.ajaxSettings.traditional = true;
See the documentation for jQuery.param: http://api.jquery.com/jQuery.param/
Also see the release notes for this change: http://jquery14.com/day-01/jquery-14 (search for 'traditional')
In the view, generate multiple named fields (not id, as id should be unique per field), noting the use of Name not name:
#foreach (var item in Model.SomeDictionary)
{
#Html.TextBoxFor(modelItem => item.Value.SomeString, new { Name = "someString[]" })
}
Then retrieve the input field values using jQuery, so:
var myArrayValues = $('input[name="someString[]"]').map(function () { return $(this).val(); }).get();
You can use this directly in jQuery / AJAX as follows:
$.ajax({
type: "POST",
url: "/MyController/MyAction",
dataType: 'json',
data: {
someStrings: $('input[name="someString[]"]').map(function () { return $(this).val(); }).get(),
someDates: $('input[name="someDate[]"]').map(function () { return $(this).val(); }).get(),
Then in the controller action in MVC:
[HttpPost]
public JsonResult MyAction(string[] someStrings, DateTime[] someDates...

Resources