http://www.nickriggs.com/posts/post-complex-javascript-objects-to-asp-net-mvc-controllers/

 

 

Post Complex JavaScript Objects to ASP.NET MVC Controllers

Posted in ASP.NETJavaScript August 21, 2009

Use the plug-in postify.js to handle posting complex JavaScript objects to ASP.NET MVC controllers using the default model binder

There is a lot on conversation going on about binding complex JavaScript objects to ASP.NET MVC actions. Complex objects are objects that have sub objects and/or arrays.

Let’s assume the following complex model:

I have a Person object with some properties, an array of phone numbers and an Address object. I would like to pass a JavaScript representation of this object to our Controller’s Create action:

?

1

2

3

4

5

6

7

8

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create(Person person)

{

//Code to add the person goes here

//return the view

return View();

}

On the client, the JavaScript representation of a Person would be:

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

var myPerson = {

FirstName: "Nick",

LastName: "Riggs",

Age: 29,

Address: {

Street: "2780 Somewhere Far",

City: "Birmingham",

State: "AL"

},

PhoneNumbers: [

"205-555-5634",

"205-555-2294",

"205-555-7681"

]

};

One way to send this object to our Controller is to “stringify” the object into a JSON string using a plugin like toJSON. However, this requires us to change the Action to accept a string instead of a typed parameter, and then deserialize the string using the JavaScriptSerializer. I can get around this by automating the deserialization with a custom ActionFilterAttribute or ModelBinder. But, what if I want to use the built-in DefaultModelBinder functionality?

The default model binding in ASP.NET MVC works based on form post data. For example, if I were going to post a simple version of Person and have ASP.NET MVC map it to our action’s person parameter, I could post:

?

1

2

3

person.FirstName: Nick

person.LastName: Riggs

person.Age: 29

ASP.NET MVC does a good job of recognizing this post data as being a Person and mapping it as such. On top of that, it has its own simple yet powerful syntax for representing more complex objects, such as this:

?

1

2

3

4

5

6

7

8

9

person.FirstName: Nick

person.LastName: Riggs

person.Age: 29

person.PhoneNumbers[0]: 205-555-5634

person.PhoneNumbers[1]: 205-555-5634

person.PhoneNumbers[2]: 205-555-5634

person.Address.Street: 2780 Somewhere Far

person.Address.City: Birmingham

person.Address.State: AL

So, instead of stringifying my JavaScript objects, I will postify them! (I made the word postify™ up, it’s mine now). My custom postify plug-in will do the work. Here is the source code:

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

$.postify = function(value) {

var result = {};

var buildResult = function(object, prefix) {

for (var key in object) {

var postKey = isFinite(key)

? (prefix != "" ? prefix : "") + "[" + key + "]"

: (prefix != "" ? prefix + "." : "") + key;

switch (typeof (object[key])) {

case "number": case "string": case "boolean":

result[postKey] = object[key];

break;

case "object":

if (object[key].toUTCString)

result[postKey] = object[key].toUTCString().replace("UTC", "GMT");

else {

buildResult(object[key], postKey != "" ? postKey : key);

}

}

}

};

buildResult(value, "");

return result;

};

This is the first cut of the plug-in, and I’m sure it’s missing something – I’ll update the source code as I make updates. That said, the plug-in greatly simplifies posting complex objects to ASP.NET MVC controllers. Here is a sample in jQuery that posts myPerson:

?

1

2

3

4

5

$.ajax({

type: "POST",

url: "/People/Create",

data: $.postify(myPerson)

});

That’s it! The plugin will handle formatting the data in an ASP.NET MVC post-friendly manner. On the server side, the parameter inflates nicely using the default model binder:

If you need to post to an action that takes multiple parameters, the complex object must be prefixed with the name of the parameter – in our case, Person. To include another parameter, use this syntax:

?

1

2

3

4

5

6

7

8

$.ajax({

type: "POST",

url: "/JSON/DoSomething",

data: $.postify({

person: myPerson,

otherParam: true

})

});

Post Complex JavaScript Objects to ASP.NET MVC Controllers的更多相关文章

  1. ASP.NET MVC Controllers and Actions

    MVC应用程序里的URL请求是通过控制器Controller处理的,不管是请求视图页面的GET请求,还是传递数据到服务端处理的Post请求都是通过Controller来处理的,先看一个简单的Contr ...

  2. [引]ASP.NET MVC 4 Content Map

    本文转自:http://msdn.microsoft.com/en-us/library/gg416514(v=vs.108).aspx The Model-View-Controller (MVC) ...

  3. SignalR + KnockoutJS + ASP.NET MVC 实现井字游戏

    SignalR + KnockoutJS + ASP.NET MVC 实现井字游戏   1.1.1 摘要 今天,我们将使用SignalR + KnockoutJS + ASP.NET MVC实现一个实 ...

  4. A Look at the Razor View Engine in ASP.NET MVC

    The biggest architectural difference that exists between ASP.NET MVC and ASP.NET Web Forms is the ne ...

  5. ASP.NET MVC HttpVerbs.Delete/Put Routes not firing

    原文地址: https://weblog.west-wind.com/posts/2015/Apr/09/ASPNET-MVC-HttpVerbsDeletePut-Routes-not-firing ...

  6. ASP.NET MVC使用Bootstrap系列(4)——使用JavaScript插件

    阅读目录 序言 Data属性 VS 编程API 下拉菜单(dropdown.js) 模态框(modal.js) 标签页(tab.js) 工具提示(tooltip.js) 弹出框(popover.js) ...

  7. 转载:Unobtrusive JavaScript in ASP.NET MVC 3 隐式的脚本在MVC3

    Unobtrusive JavaScript 是什么? <!--以下是常规Javascript下写出来的Ajax--> <div id="test"> &l ...

  8. [asp.net mvc 奇淫巧技] 05 - 扩展ScriptBundle,支持混淆加密javascript

    一.需求: 在web开发中,经常会处理javascript的一些问题,其中就包括js的压缩,合并,发布版本以及混淆加密等等问题.在asp.net 开发中我们使用ScriptBundle已经可以解决ja ...

  9. ASP.NET MVC Bundles 用法和说明(打包javascript和css)

    本文主要介绍了ASP.NET MVC中的新功能Bundles,利用Bundles可以将javascript和css文件打包压缩,并且可以区分调试和非调试,在调试时不进行压缩,以原始方式显示出来,以方便 ...

随机推荐

  1. 针对电信乌龙事件的深度测试: 广州电信错误将深圳地区189的号码在3G升级4G申请时从广州网厅发货,造成深圳用户收到4G卡后无法激活,深圳电信找不到订单

    广州电信错误将深圳地区189的3G升级4G申请从中国电信广州网厅发货(智能卡号:8986 1114 9002 0851  742X S  电话号码 189),造成用户收到4G卡后无法激活,深圳电信找不 ...

  2. WEB ui快速构建

    http://www.runoob.com/bootstrap/bootstrap-ui-editor.html 1http://pingendo.com/ 2http://www.layoutit. ...

  3. .NET项目框架(转)

    摘要:本文描述了在用VS.NET进行B/S开发时采用的框架结构,一般建立类库项目和Web项目,在Web基本aspx页面类中调用类库中方法,同时在aspx页面类中不需要写任何对数据库操作的SQL代码,便 ...

  4. 网络图片下载缓存库SDWebImage的使用

    SDWebImage导入问题 最新的SDWebImage由于是基于ARC模式写的,如果创建的是非ARC醒目的童鞋们注意,导入文件夹之后,先添加ImageIO.framework,mapKit.fram ...

  5. 安装VMware Tools找不到内核头文件

    http://blog.csdn.net/bobbat/article/details/38568885 安装VMware Tools,解决无法找到kernel header path的问题 安装 V ...

  6. 我与python3擦肩而过(一)—— Dict与collections.OrderredDict邂逅

    最近一直在撸Python Data Analysis上的代码(书是基于Python2的,小白我用的python3),所以我下的时候多少有些改动. 这是9.4中的nltk词频分析关于Dict_key的问 ...

  7. Nunit 使用介绍

    Nunit是.NET平台单元测试框架,其是从Junit发展而来,它强大之处是支持所有的.NET语言. Nunit的下载地址:http://www.nunit.org 介绍1: 布局: 左面:我们写的每 ...

  8. flex+java将数据库里的数据导出到指定目录下excel表里(poi)

    数据写入到excel中采用的是Apache POI: //java后台的一个工具类(该工具类适用于为不同字段添加,方便) /* 下面这个方法是将list转换为Excel工作表的 */ public s ...

  9. Aborting commit: 'XXXXXXXX'remains in conflict错误

    今天在提交项目文件到本地SVN时提示错误如下: 过期:”global.php“在事务”21-1“, You have to update your working copy first. 运行upda ...

  10. Day03_JAVA语言基础第三天

    1.位运算符 1.面试题(掌握) ^:一个数据对同一个数据^两次,结果还是数据本身 举例:a ^ b ^ b = a  2.注意 知道结论,面试题,以后就完全不用看了 2.逻辑运算符(掌握)     ...