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. 在windows上搭建ftp服务

    在控制面板->程序和功能->打开或关闭Windows功能中开启ftp和IIS信息服务管理器 在控制面板->管理工具中打开Internet信息服务管理器->添加ftp站点 建好之 ...

  2. 前端开发者应该知道的 CSS 小技巧

    一些小技巧让你的CSS技术更专业 使用:not()去除导航上不需要的边框 为body添加行高 垂直居中任何元素 逗号分离的列表 使用负nth-child选择元素 使用SVG图标 文本显示优化 在纯CS ...

  3. 【LeetCode OJ】Best Time to Buy and Sell Stock II

    Problem Link: http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ We solve this prob ...

  4. EF中逆变和协变

    EF中的增删改查: 实现步骤: 1.声明一个EF的上下文. bjhksjEntities dbContext = new bjhksjEntities(); 2.声明一个实体. HKSJ_USERS ...

  5. Unity3D ShaderLab 漫反射卷积光照模型

    Unity3D ShaderLab 漫反射卷积光照模型 漫反射卷积[Diffuse convolution]是一个模糊立方体的过程,它保留了立方图的整体光照强度,只模糊了细节. 这种效果在我们要活得一 ...

  6. dat文件中如何编写DOS的多行命令

    dat文件中如何编写DOS的多行命令 2012-10-15 11:29 四海柔情108 分享到:   2012-10-16 23:36 提问者采纳   你问的应该是BAT文件吧?BAT是DOS命令的批 ...

  7. Ubuntu安装文泉驿-微米黑字体

    sudo apt-get install ttf-wqy-microhei #文泉驿-微米黑

  8. Struts2 OGNL使用详解(转)

    OGNL OGNL ( Object Graph Navigation Language ),对象图导航语言.这是一种强大的表达式语言,通过它可以非常方便的来操作对象属性. 在 Struts2 中,O ...

  9. 2.0.4 CCLabelTTF在ios7下不显示的问题

    要修改框架lib目录里的 CCImage.mm,就是把浮点值取了个整,之前的浮点形导致绘制失败: 在_initWithString这个方法里把如下代码替换一下就行了: //////////////// ...

  10. node实现http上传文件进度条 -我们到底能走多远系列(37)

    我们到底能走多远系列(37) 扯淡: 又到了一年一度的跳槽季,相信你一定准备好了,每每跳槽,总有好多的路让你选,我们的未来也正是这一个个选择机会组合起来的结果,所以尽可能的找出自己想要的是什么再做决定 ...