Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX Post Multiple Data to ASP.Net MVC

I am facing problem while posting multiple objects via ajax jquery to MVC 4 controller. It has been weeks but I can't seem to find a solution. I tried several approaches, sometimes the filterModel object is null and sometimes string parameters are null (doesn't matter even if I stringify of if I specify contentType or not)

What I want? I want to pass three objects: 1. filterModel 2.testparamA 3.testparamB What should I do to pass all three objects to MVC controller? What do I need to write in data: so I get all 3 object values?

The simplest 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"
        });
    }
}

The simplest 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 simplest 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; }
}
like image 274
suomi-dev Avatar asked Aug 13 '14 14:08

suomi-dev


1 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 })
like image 144
Paul Zahra Avatar answered Oct 13 '22 11:10

Paul Zahra