use of GET and POST by ASp.net MVC - asp.net-mvc

I would like to now the difference for ASP.net MVC between two calls of the same action :
public class VisualizzareAreaIntervento
{
public string Descrizione { get; set; }
public int PageNum { get; set; }
public int PageSize { get; set; }
}
public JsonResult GetItems(VisualizzareAreaIntervento command){
...
}
If I call it via Post, everything works fine and the aprameter command in the action is well initialised:
var command = new VisualizzareItems(descrizione,pageNum,pageSize);
$.ajax({
type: 'Post',
url: '#Url.Action("GetItems")',
data: JSON.stringify(command),
contentType: 'application/json; charset=utf-8',
success: success,
error: error,
dataType: 'json'
});
the same call with Get, gives me an command object with default values in it ("",0,0)
var command = new VisualizzareItems(descrizione,pageNum,pageSize);
$.ajax({
type: 'Get',
url: '#Url.Action("GetItems")',
data: JSON.stringify(command),
contentType: 'application/json; charset=utf-8',
success: success,
error: error,
dataType: 'json'
});
I have looked in firebug and the object is well sent the two times. How does ASP.net MVC works this out?
thanks for your support,

Short answer: DefaultModelBinder.
Old link, but it will make you get the basics:
http://www.howmvcworks.net/OnModelsAndViewModels/TheBeautyThatIsTheModelBinder

Related

MVC Model properties are null when calling post mvc action via ajax call

I have below lines of code in controller, model and in js file.
I am able to make call to controller, but model properties are always null.
...
[HttpPost]
public IActionResult CreateBooking(Country request)
{
return Ok();
}
public class Country
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
}
var request = {
name: 'Prateek',
code: 'US'
};
$.ajax('/Home/CreateBooking', {
data: JSON.stringify({ request }),
contentType: 'application/json',
type: 'POST',
dataType: 'json',
success: function (response) {},
error: function(response){}
Can anyone help please?
Thanks in advance
var request = jQuery.parseJSON('{ "Name": "Prateek", "Code": "US" }');
$.ajax({
url: "/Home/CreateBooking",
type: "POST",
dataType: "JSON",
data: request,
success: function (d) {
},
error: function (d) {
console.log(d);
}
});

Json not parsing correctly from jQuery AJAX call in MVC4

I am passing back Json via a jQuery AJAX call to a MVC function that takes a Folder. MVC correctly parses some of the data but not the list I sent back.
MVC
public class Folder : IValidate
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<SearchCriteria> SearchCriteria { get; set; }
}
public class SearchCriteria
{
public int FolderId { get; set; }
public int SettingsEntryID { get; set; }
public string SearchParameter { get; set; }
}
public ActionResult EditFolder(Folder folder)
{
service.EditFolder(folder);
return this.Json(Json(new { Success = true }));
}
Javascript
var folder = {
Id: $("#groupID").val(),
Name: $("#groupName").val(),
SearchCriteria: []
};
$(".searchCriteria").each(function () {
folder.SearchCriteria.push(
{
FolderId: $("#groupID").val(),
SearchParameter: $(this).val(),
SettingsEntryID: $(this).attr("id").replace("searchCriteria", "")
});
});
$.ajax({
url: "/settings/editfolder/",
type: "POST",
dataType: "json",
data: folder,
traditional: true,
success: function (data) {
alert("wsaved");
}
});
folder, in this function gets set with Id and Name but SearchCriteria is not set properly. It is set to null. If I comment out the traditional: true the list gets created but all the values for each SearchCriteria are 0 or null.
Am I missing something?
You are missing two points
1. contentType: 'application/json; charset=utf-8',
2. data: JSON.stringify(folder)
And one correction.
URL should be like
url : "#Url.Action("ActionName", "ControllerName", new { area = "AreaName" })"
jQuery
$.ajax({
url: "#Url.Action("Action", "Controller", new { area = "Area" })",
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(folder),
traditional: true,
success: function (data) {
alert("wsaved");
}
});

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.

Kendo UI - Ajax MVC - JSON always null

I have a Kendo grid that has been sort-enabled. I want to do an ajax postback using jQuery to send the sort information to the action method to do some action.
var datasource = $(".data-table").data("kendoGrid").dataSource;
$.ajax({
type: 'POST',
url: '#Url.Action("ExportToPDf", "MyController")',
dataType: 'json',
data: { sort: datasource._sort }
});
I'm able to see with a debugger that the correct value is got and passed in the data attribute of the ajax. I used FireBug to confirm that the values are passed during the POST action.
public ActionResult ExportToPDf(List<SortDescription> sort)
{
//Will be doing some action
return null;
}
public class SortDescription
{
public string dir { get; set; }
public string field { get; set; }
}
Sample data from Firebug during POST action
sort[0][dir] asc
sort[0][field] EmployeeRef
When I keep breakpoint in action method, im able to get one item in the list, but the properties appear to be null.
Can anyone please guide me what I do wrong?
Try something like this:
$.ajax({
url: '#Url.Action("ExportToPDf", "MyController")',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({sort: datasource._sort })
})

Model binder does not convert json to IEnumerable<T>

I am sending json data to my controller action via jquery ajax post. The IEnumerable in my action is alway null.
Is my json wrong or why does the model binder not convert the json to the IEnumerable ?
public ActionResult Update(IEnumerable<Teststep> teststeps)
{
//
}
$.ajax({
url: '#Url.Action("Update", "Teststep")',
type: 'POST',
data: [{ "errortext": "oh something bad happended.", "unitid": "10" }, { "errortext": "you got it man.", "unitid": "20"}],
success: function (response) {
debugger;
if (response.success) {
dlg.dialog("close");
// Update UI
}
else {
// Reload the dialog with the form to show model/validation errors
dlg.html(response);
}
}
});
public class Teststep
{
[HiddenInput(DisplayValue = false)]
public int UnitId { get; set; }
public string ErrorText { get; set; }
// some other props removed for readability
}
In order to get collections (arrays, ienumerables, etc) to pass correctly through the modelbinder to the action method, I've always had to set the traditional: true option on the ajax call:
$.ajax({
url: '#Url.Action("Update", "Teststep")',
type: 'POST',
traditional: true,
...
Now it works! I get 1 item in the IEnumerable. The problem was the messed up json ;-)
var data = { teststeps: [{ ErrorText: 'bla', UnitId: 10}] };
$.ajax({
url: '#Url.Action("Update", "Teststep")',
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json'
});
[HttpPost]
public ActionResult Update(IEnumerable<Teststep> teststeps)
{
}

Resources