使用AJAX向ASP.Net MVC发送多个数据的POST请求

6
我在使用ajax jquery向MVC 4控制器发布多个对象时遇到了问题。已经过了几周了,但我似乎找不到解决办法。
我尝试了几种方法,有时filterModel对象为空,有时字符串参数为空(无论我是否stringify或指定contentType)。
我想要什么? 我想传递三个对象:1.filterModel 2.testparamA 3.testparamB。 我该怎么做才能将这三个对象全部传递给MVC控制器?我需要在data:中编写什么来获取所有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; }
}

1
你为 FilterModel 编写了 ModelBinder 吗? - Philipp M
你是说 data: JSON.stringify({ fm: filterModel, ta: testparamA, tb: testparamA }) 不起作用吗?请阅读 https://dev59.com/dmkw5IYBdhLWcg3w6e0b - Paul Zahra
@PhilippM 我没有编写ModelBinder。它应该由MVC自动绑定,因为data: filterModel可以完美地将数据发送到MVC。但是data: {filter: filterModel,testparamA: 'A value',testparamB: 'B value'}不起作用。 - suomi-dev
如果您有一个ModelBinder,MVC将区分FilterModel对象和平面参数,我认为,但我现在无法测试它。 - Philipp M
1
@PaulZahra 谢谢。现在我意识到应该将整个东西字符串化,而不仅仅是 filterModel :) 很高兴它起作用了 :) - suomi-dev
请看这个答案:https://dev59.com/dXVC5IYBdhLWcg3wZwJT#310136 - dwbrito
2个回答

4

希望您不介意我将我的评论(很有帮助)发布为答案...

如果您按照以下方式使用stringify,它应该可以工作...

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

使用 $.ajax post 和 { datatype: 'json' ...} 可以很好地工作。 - Dan Randolph

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接