AJAX将多个数据发布到ASP.Net MVC

时间:2014-08-13 14:01:30

标签: c# jquery ajax asp.net-mvc-4

我在通过ajax jquery向MVC 4控制器发布多个对象时遇到问题。已经好几周了,但我似乎无法找到解决方案。 我尝试了几种方法,有时filterModel对象为null,有时字符串参数为null(即使我指定了contentType,我也无关紧要)

我想要什么? 我想传递三个对象:1。filterModel 2.testparamA 3.testparamB 如何将所有三个对象传递给MVC控制器?我需要在数据中写什么:所以我得到所有3个对象值?

最简单的控制器

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

最简单的视图

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();

最简单的FilterModel类

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; }
}

2 个答案:

答案 0 :(得分:3)

希望你不介意我发表评论(这很有帮助)作为答案...

如果您按如下方式使用stringify,它应该有效......

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

答案 1 :(得分:0)

@PaulZahra引导我走向正确的方向。

  

以下更改解决了我的问题:

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