MVC4 JSON模型绑定不工作[英] MVC4 JSON Model Binding doesn't work

本文是小编为大家收集整理的关于MVC4 JSON模型绑定不工作的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

本文来自:IT宝库(https://www.itbaoku.cn)

使用以下ViewModel:

public class GetUsersFromNextCircuitRequest
    {
        public int? dosarId { get; set; }
        public List<int> dosareIds { get; set; }
        public string query { get; set; }
        public int page { get; set; }
        public int page_limit { get; set; }
    }

并在以下操作中使用它:

 public ActionResult GetUsersFromNextCircuit(GetUsersFromNextCircuitRequest requestNextUsers)
        {
         }

并以以下方式发送请求:

ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                    url: self.attr('getusersfromnextcircuiturl'),
                    dataType: "json",
                    contentType: 'application/json; charset=utf-8',
                    type: 'POST',
                    traditional: true,
                    data: function (term, page) {
                        if (self.attr('dosare') !== undefined && self.attr('dosare').length > 0) {
                            var dosareIds = [];
                            self.attr('dosare').forEach(function (element, index, list) {
                                dosareIds.push(element.attr('Id'));
                            });
                            return JSON.stringify({
                                    query: term, // search term
                                    page: page,
                                    dosareIds: dosareIds,
                                    page_limit: 30

                            });
                        }
                        else
                            return JSON.stringify({
                                    query: term, // search term
                                    page: page,
                                    dosarId: self.attr('dosarid'),
                                    page_limit: 30

                            });
                    },
                    results: function (data, page) {
                        var more = (page * 30) < data.total; // whether or not there are more results available
                        return { results: data.users, more: more };
                    }
                }

HTTP请求看起来像这样:

{"query":"xa","page":1,"dosareIds":[4137,4163],"pagelimit":30}

问题是请求参数为null.我不知道为什么它不起作用.

推荐答案

我们遇到了同样的问题,然后我们决定使用Custommodelbinder.正在分享我们所做的事情,

在客户端,

在ajaxrequest中,您需要在下面发送整个ViewModel,

        var viewModel = new Object();
        viewModel.query= term;
        viewModel.page= page;
        viewModel.dosareIds= new Array();
        viewModel.dosarIds = dosareIds;
        viewModel.page_limit = 30;

然后将模型串起并分配给数据

data: { viewModel: JSON.stringify(viewModel) };

在服务器端,

您可以使用Custommodelbinder来检索后面的值

public class CustomJsonModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        try
        {
            var data = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            JavaScriptSerializer js = new JavaScriptSerializer();
            var temp = js.Deserialize(data.AttemptedValue, bindingContext.ModelType);
            return temp;
        }
        catch
        {
            return null;
        }
    }
}

和在Ur ViewModel中,您需要添加属性,

[ModelBinder(typeof(CustomJsonModelBinder))]
public class GetUsersFromNextCircuitRequest
{
    public int? dosarId { get; set; }
    public List<int> dosareIds { get; set; }
    public string query { get; set; }
    public int page { get; set; }
    public int page_limit { get; set; }
}

现在,CustomJsonModelBinder将解析该值.我希望它能解决您的问题.

本文地址:https://www.itbaoku.cn/post/293271.html

问题描述

Using the following Viewmodel :

public class GetUsersFromNextCircuitRequest
    {
        public int? dosarId { get; set; }
        public List<int> dosareIds { get; set; }
        public string query { get; set; }
        public int page { get; set; }
        public int page_limit { get; set; }
    }

and using it in the following action:

 public ActionResult GetUsersFromNextCircuit(GetUsersFromNextCircuitRequest requestNextUsers)
        {
         }

and send the request the following way:

ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
                    url: self.attr('getusersfromnextcircuiturl'),
                    dataType: "json",
                    contentType: 'application/json; charset=utf-8',
                    type: 'POST',
                    traditional: true,
                    data: function (term, page) {
                        if (self.attr('dosare') !== undefined && self.attr('dosare').length > 0) {
                            var dosareIds = [];
                            self.attr('dosare').forEach(function (element, index, list) {
                                dosareIds.push(element.attr('Id'));
                            });
                            return JSON.stringify({
                                    query: term, // search term
                                    page: page,
                                    dosareIds: dosareIds,
                                    page_limit: 30

                            });
                        }
                        else
                            return JSON.stringify({
                                    query: term, // search term
                                    page: page,
                                    dosarId: self.attr('dosarid'),
                                    page_limit: 30

                            });
                    },
                    results: function (data, page) {
                        var more = (page * 30) < data.total; // whether or not there are more results available
                        return { results: data.users, more: more };
                    }
                }

The http request looks like this:

{"query":"xa","page":1,"dosareIds":[4137,4163],"pagelimit":30}

The problem is that the request parameter is null. I have no idea why it doesn't work.

推荐答案

We had the same problem, then we decided to use CustomModelBinder. Am sharing what we have done,

In client side,

In ajaxRequest u need to send the entire ViewModel as below,

        var viewModel = new Object();
        viewModel.query= term;
        viewModel.page= page;
        viewModel.dosareIds= new Array();
        viewModel.dosarIds = dosareIds;
        viewModel.page_limit = 30;

then stringify the model and assign it to the data,

data: { viewModel: JSON.stringify(viewModel) };

In Server side,

U can use customModelBinder to retrive the value back

public class CustomJsonModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        try
        {
            var data = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            JavaScriptSerializer js = new JavaScriptSerializer();
            var temp = js.Deserialize(data.AttemptedValue, bindingContext.ModelType);
            return temp;
        }
        catch
        {
            return null;
        }
    }
}

And in ur viewModel u need to add the attribute,

[ModelBinder(typeof(CustomJsonModelBinder))]
public class GetUsersFromNextCircuitRequest
{
    public int? dosarId { get; set; }
    public List<int> dosareIds { get; set; }
    public string query { get; set; }
    public int page { get; set; }
    public int page_limit { get; set; }
}

Now, CustomJsonModelBinder will parse the value. I hope it will solve ur prob.