I ran into a problem when sending multiple objects via ajax jquery to MVC 4 controller. Weeks passed, but I can not find a solution. I tried several approaches, sometimes the filterModel object is null, and sometimes the string parameters are null (it doesnβt matter even if I strict if I specify the contentType type or not)
What do I want? I want to pass three objects: 1. filterModel 2.testparamA 3.testparamB What should I do to transfer all three objects to the MVC? What do I need to write in the data: so that I get all 3 values ββof the object?
The easiest controller
[HttpPost] public JsonResult Test(string testparamA, string testparamB, FilterModel filter) { using (RBSystemEntities repository = new RBSystemEntities()) { return Json(new { DataList = repository.Items.Select(x => new {x.PKID, x.ItemName}).ToList(), Result = "OK" }); } }
Easiest view
var filterModel = @Html.Raw(Json.Encode(new FilterModel("ItemName", "Pepperoni Pizza"))) //filterModel = JSON.stringify(filterModel); function testme() { // post the javascript variable back to the controller $.ajax({ url: '/Menu/Test', type: 'POST', //contentType: 'application/json; charset=utf-8', data: { filter: filterModel, testparamA: 'A value', testparamB: 'B value' }, // with this approach I get filterModel null in the controller however testparamA and testparamB has values data: filterModel, // with this approach I get values for filterModel but I can't pass testparamA and testparamB success: function (result) { // TODO: do something with the results alert('success'); } }); } testme();
The easiest FilterModel class
public class FilterModel { public FilterModel() { } public FilterModel(string filtercolumn, string filtervalue) { this.FilterColumn = filtercolumn; this.FilterValue = filtervalue; this.FilterColumnCriteria = "="; } public string FilterColumn { get; set; } public string FilterValue { get; set; } public string FilterColumnCriteria { get; set; } }
source share