AJAX sends some data to ASP.Net MVC

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; } } 
+6
source share
2 answers

Hope you don't mind me posting my comment (which was helpful) as an answer ...

If you use stringify as follows, it should work ...

 JSON.stringify({ fm: filterModel, ta: testparamA, tb: testparamA }) 
+4
source

@PaulZahra directed me in the right direction.

Below is my problem changed:

 contentType: 'application/json; charset=utf-8', // uncomment this data: JSON.stringify({ filter: filterModel, testparamA: 'A value', testparamB: 'B value' }), //stringify whole thing and not just c# class 
0
source

Source: https://habr.com/ru/post/973767/


All Articles