Home  >  Article  >  Backend Development  >  Model binding example tutorial using Action

Model binding example tutorial using Action

零下一度
零下一度Original
2017-06-24 10:38:031601browse

In QQ groups or some program communication platforms, people often ask: How do I pass an array and receive it in Action? Why can't the array I pass be received in Action's model, or I set some arrays in ajax data, why the background still can't receive it , and some How to send a complex object or How to receive one in Action Complex objects and other issues. Or when some people encounter complex objects or arrays, they directly transfer a json string, and then convert the json string into a model object in Action. Of course, this is also an approach, but it may not be the best approach.

1. Requirements

According to the data format shown in the figure, it is passed to Action and received by a UserInfo Model. The requirements are very simple.

After analysis, we can see that the hobby is an array of strings, the user contains a company object, and then the included company object also has a phone array, and the user It also contains array objects, so our Model should be:

public class UserInfo
{public string Name { get; set; }public int Age { get; set; }public string[] Bobbys { get; set; }public Company Company { get; set; }public Star[] Star { get; set; }
}public class Company
{public string Name { get; set; }public string Address { get; set; }public string[] Tel { get; set; }
}public class Star
{public string Name { get; set; }public int Age { get; set; }public string Movie { get; set; }
}

2. Form submission literacy and verification

We don’t care when submitting the form Whether it is a post or a get submission, most of the data we submit is in the format of key-value pairs. We will not directly pass in a json object to the background. At most, we will only pass in a string of json. , this may be misled by the ajax data settings. Many people think that you can directly set the json object to submit to the background. Maybe a model with a simple format can be received, but a more complicated one, such as one containing an array, etc., even if the json format is the same as The format of the Model is consistent, and the Model will not receive the array data submitted by the front end. This is also a question I raised at the beginning of the article.

In order to verify that ajax submits data in json format, let’s do some verification.

Action:

[HttpPost]public ActionResult Index(UserInfo user)
{return Json(user);
}

Ajax:

$.ajax({
    url: "/",
    type: "post",
    data: {"name": "Emrys",
        "age": "26",
        "bobbys": ["足球", "电影"],
        "company": {
            "name": "上海xxxxxx公司",
            "address": "上海徐汇区xxxx路",
            "tel": [
                "021-88888881",
                "021-88888882",
                "021-88888883",
                "021-88888884"
            ]
        },
        "star": [
            { "name": "成龙", "age": "63", "movie": "十二生肖" },
            { "name": "刘亦菲", "age": "18", "movie": "功夫之王" },
            { "name": "胡歌", "age": "24", "movie": "琅琊榜" }
        ]
    },
    success: function (r) {
        console.log(r);
    }
});

 这个是我们经常提交的data数据格式,如果我们后台的model格式即使和data的数据格式一模一样,也只有name一项可以正常接收到数据,其他的所有数据都将接收不到,至于为什么。我们看一下jquery给我们转成的键值对的格式就应该知道了,我们从chrome或者火狐的调试工具的network中可以看到提交的格式。

其中数组的格式为:xxxxxx[]的格式,对象中的对象格式为xxxx[yyyyy]格式,我没有探究为什么是这个格式,也许是其他的语言需要这样的格式,php,jsp或者其他的语言吧,但asp.net mvc很明显不需要这样的格式。

后面是毁三观的验证,结果结果竟然全都能用Model接收到数据,接收到了,接收到,接收,接,了,我。。。。。。。。。突然感觉有一百个那个什么飞过啊。。。。。。。。。。

我一度怀疑自己,难道之前做了几年mvc的开发的模型绑定理解错了,之前开发用jquery的ajax转成的格式是不能接收到数据的啊,那是为什么为什么啊。经过探索测试发现,我之前也没有理解错,原来是版本的问题。我测试是用的mvc5做的测试,mvc5可能对jquery ajax转成的格式做了优化,但是mvc5之前的版本是不可以的,这个是重点

那也就是说,如果你用的mvc5做的开发,反而简单了很多,可以直接在ajax的data设置json格式的数据,复杂的,数组都可以,也许微软开发人员也发现了这个问题,在mvc5解决了,我并没有去研究源码的区别,总之呢,mvc5是可以的。那mvc5以前的版本就会遇到我说的那个问题了。  

 

三、模型绑定分析

博客模拟的表单已经可以包含网站开发过程中遇到的大部分的表单格式了,包含一些数组、对象等等。

从以前的开发的mvc项目中,发现了一些模型绑定的规律,区别在于数组和对象中的对象。

下面的图片是手动转成键值对的值,mvc5之前的版本可以适用的格式,当然mvc5也是可以识别的,或者说这个格式是所有的mvc版本都可以适用的格式。

下图是两种格式的对比图

 

关于其中的规则,自己总结吧,应该很简单了。

有人会问,手动拼的格式应该怎么拼呢,这里经常用的有两种格式。

1、直接拼接字符串

$.ajax({
    url: "/",
    type: "post",
    data: "name=Emrys&age=26&bobbys[0]=足球&star[0].movie=琅琊榜",
    success: function (r) {
        console.log(r);
    }
});

 

2、javascript对象

var data1 = { name: "Emrys" };
data1.age = 26;
data1["bobbys[0]"] = "足球";
data1["star[0].movie"] = "琅琊榜"; 

$.ajax({
    url: "/",
    type: "post",
    data: data1,
    success: function (r) {
        console.log("xxxxxxxxxxxxxx");
        console.log(r);
    }
});

用户可以根据情况选择不同的拼接方式。

 

四、总结

顺便分享一个技巧,就是当我们拿到一段json的时候,别急着在类中新建model,一个一个类,一个一个的属相敲,vs已经提供了一个很强大的工具,知道的可以忽略本段。

 

源码地址Github:

以上就是关于模型绑定的一些应用,本文原创,欢迎拍砖和推荐。   

系列课程

  • [asp.net mvc 奇淫巧技] 01 - 封装上下文 - 在View中获取自定义的上下文

  • [asp.net mvc 奇淫巧技] 02 - 巧用Razor引擎在Action内生成Html代码

  • [asp.net mvc 奇淫巧技] 03 - 枚举特性扩展解决枚举命名问题和支持HtmlHelper

  • [asp.net mvc 奇淫巧技] 04 - 你真的会用Action的模型绑定吗?

 

The above is the detailed content of Model binding example tutorial using Action. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn