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

2024-03-28

我在通过 ajax jquery 将多个对象发布到 MVC 4 控制器时遇到问题。已经过去几周了,但我似乎找不到解决方案。 我尝试了几种方法,有时filterModel对象为空,有时字符串参数为空(即使我对是否指定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; }
}

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

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

JSON.stringify({ fm: filterModel, ta: testparamA, tb: testparamA })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AJAX 将多个数据发送到 ASP.Net MVC 的相关文章

随机推荐