搜索
首页后端开发C#.Net教程使用Action的模型绑定实例教程
使用Action的模型绑定实例教程Jun 24, 2017 am 10:38 AM
actionasp.net

在QQ群或者一些程序的交流平台,经常会有人问:我怎么传一个数组在Action中接收、我传的数组为什么Action的model中接收不到、或者我在ajax的data中设置了一些数组,为什么后台还是接收不了、还有一些怎么传送一个复杂的对象或者Action怎么接收一个复杂的对象等等这些问题。或者有些人遇到复杂的对象或者数组直接就传送个json字符串,然后在Action中把json字符串转成model对象,当然这也是一种做法,但也许不是最优的做法。

 

一、需求

按照如图的数据格式,传入到Action,用一个UserInfo Model接收,需求非常简单。

分析后我们可以看到,其中爱好是个字符串的数组,用户包含一个公司对象,然后所包含的公司对象中又有个电话数组,用户又包含数组对象,所以我们的Model应该是:

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; }
}

 

二、表单提交扫盲与验证

我们在提交表单时不管是post还是get提交,我们所提交的数据大部分都是键值对的格式,并不会直接传入个json对象至后台,最多也只会传入个字符串的json,这个也许是受ajax data设置的误导,很多人都会认为可以直接设置json对象提交至后台,也许格式简单的Model可以接收到,但是复杂一点的,比如其中包含数组的等,即使json的格式和Model的格式一致,Model并不会接收到前台的提交的数组数据,这个也是我文章刚开始所提的一个问题。

为了验证我说的ajax提交json格式的数据,我们做一下验证。

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的模型绑定吗?

 

以上是使用Action的模型绑定实例教程的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
DJI Osmo Action 5 Pro: Release date mooted as retailer reveals launch pricing that could undercut GoPro Hero 13 BlackDJI Osmo Action 5 Pro: Release date mooted as retailer reveals launch pricing that could undercut GoPro Hero 13 BlackSep 04, 2024 am 06:51 AM

DJI has not confirmed any plans to introduce a new action camera yet. Instead, it seems that GoPro will get ahead of its rival this year, having teased that it will introduce two new action cameras on September 4. For context, these are expected to a

Insta360 Go 3S: New pocketable 4K action camera released weighing just 39 g with Apple Find My supportInsta360 Go 3S: New pocketable 4K action camera released weighing just 39 g with Apple Find My supportJun 14, 2024 pm 06:05 PM

Insta360hasreleasedanewactioncamera,itssecondoftheyearaftertheInsta360X4(curr.$499.99onAmazon).Asexpected,thecompanyhasintroducedtheGo3S,anupgradedthatGo3thatadds4Kvideorecordingcapabilities.Specifically,whileInst

New DJI Osmo action camera spotted before probable summer 2024 launch to rival recent GoPro and Insta360 releasesNew DJI Osmo action camera spotted before probable summer 2024 launch to rival recent GoPro and Insta360 releasesJul 01, 2024 am 09:49 AM

Almost a year has passed since DJI released the Osmo Action 4 (curr. $299 on Amazon). Since then, the company has focused on its other divisions, including new RS camera gimbals. On top of that, it has introduced various drones as well like the Avata

Vuex状态管理之Action异步操作详解Vuex状态管理之Action异步操作详解Aug 10, 2022 pm 03:29 PM

某些情况,我们希望在Vuex中进行一些异步操作, 比如网络请求, 必然是异步的,这个时候怎么处理呢?下面就给大家介绍Vuex状态管理之Action异步操作,希望对需要的朋友有所帮助!

GoPro releases new Hero 13 Black action camera with new lens mods alongside curious GoPro HeroGoPro releases new Hero 13 Black action camera with new lens mods alongside curious GoPro HeroSep 05, 2024 am 06:45 AM

GoPro has now introduced its annual action camera refresh. Unlike in recent years, the company has decided to release two models. However, it has not returned to 360-degree cameras, despite teasing this time last year that it would replace the Max wi

elasticsearch java客户端action怎么实现elasticsearch java客户端action怎么实现May 22, 2023 am 08:43 AM

elasticsearch中的绝大部分操作都是通过相应的action,这些action在action包中。它的结构如下图所示:上图是action包的部分截图,这里面对应着各个功能的action。各个action的包也都非常类似于index。这些action的实现也非常类似,都是基础自action,下图是indexaction的继承关系:因为这些action并未真正实现相应的功能,只是一个代理,因此实现上也非常简单。他们的主要作用是提供新建response和request的方法及对应的action

GoPro Hero: New pocket-sized action camera leaks along with rumoured release dateGoPro Hero: New pocket-sized action camera leaks along with rumoured release dateAug 16, 2024 am 09:43 AM

Details of a completely new GoPro action camera has leaked online alongside equivalent information about the Hero 13 Black. Please note that the information contained below is said to originate from an Amazon US listing that has since now been remove

Deal | Amazfit GTR 3 Pro Limited Edition smartwatch with 12-day battery life, GPS and 1,000 nits AMOLED now available for just $125Deal | Amazfit GTR 3 Pro Limited Edition smartwatch with 12-day battery life, GPS and 1,000 nits AMOLED now available for just $125Aug 15, 2024 am 11:14 AM

The Amazfit GTR 3 Pro Limited Edition is currently on sale at Amazon for just $124.99, down 40% from its list price of $209.99. Compared to the standard version that has an aluminum case, the Amazfit GTR 3 Pro Limited Edition uses hand-polished stain

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器