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!

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

C#.NET is a popular choice for building microservices because of its strong ecosystem and rich support. 1) Create RESTfulAPI using ASP.NETCore to process order creation and query. 2) Use gRPC to achieve efficient communication between microservices, define and implement order services. 3) Simplify deployment and management through Docker containerized microservices.

Security best practices for C# and .NET include input verification, output encoding, exception handling, as well as authentication and authorization. 1) Use regular expressions or built-in methods to verify input to prevent malicious data from entering the system. 2) Output encoding to prevent XSS attacks, use the HttpUtility.HtmlEncode method. 3) Exception handling avoids information leakage, records errors but does not return detailed information to the user. 4) Use ASP.NETIdentity and Claims-based authorization to protect applications from unauthorized access.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.