Post Complex JavaScript Objects to ASP.NET MVC Controllers

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

})

});

时间: 2024-10-12 13:17:09

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

ASP.NET MVC Controllers and Actions

MVC应用程序里的URL请求是通过控制器Controller处理的,不管是请求视图页面的GET请求,还是传递数据到服务端处理的Post请求都是通过Controller来处理的,先看一个简单的Controlller: public class DerivedController : Controller { public ActionResult Index() { ViewBag.Message = "Hello from the DerivedController Index method&q

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 neat separation between the two key phases of processing the request and generating the response. In general, rendering an ASP.NET Web Forms page means

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

原文地址: https://weblog.west-wind.com/posts/2015/Apr/09/ASPNET-MVC-HttpVerbsDeletePut-Routes-not-firing?utm_source=tuicool&utm_medium=referral 国内:http://www.tuicool.com/articles/Zv2EbmY A few times in the last weeks I’ve run into a problem where I found

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

本文主要介绍了ASP.NET MVC中的新功能Bundles,利用Bundles可以将javascript和css文件打包压缩,并且可以区分调试和非调试,在调试时不进行压缩,以原始方式显示出来,以方便查找问题. 在网页中,我们经常需要引用大量的javascript和css文件,在加上许多javascript库都包含debug版和经过压缩的release版(比如jquery),不仅麻烦还很容易引起混乱,所以ASP.NET MVC4引入了Bundles特性,使得我们可以方便的管理javascript

ASP.NET MVC Unobtrusive JavaScript 实现 onfocusout 验证, onfocusin 清除错误(转)

在 ASP.NET MVC 中启用 Unobtrusive JavaScript 功能,可以在运行时由服务器端根据Model中设置的验证规则,自动生成客户端验证js代码(结合jquery.validate).这很好地解决了表单验证时一次代码,两次验证(客户端+服务器端)的问题. 使用它很简单,主要操作步骤如下: 1. 在web.config增加如下设置: <appSettings> <add key="ClientValidationEnabled" value=&q

通过ASP.NET MVC框架 + 原生JavaScript + Ajax + SQL SERVER 实现一个简单的有论坛功能的网站(有通过iis发布的例子)

ASP.NET MVC. M 为Model模型层, V 为View视图层, C 为Controller控制层.要想使用MVC框架来写网站就需要了解M V C 的作用分别为哪些.给大家简单的介绍一下: 1.当你的这个网站要与数据库交互的时候,你可以使用EF创建一个数据库模型,也可以用类存放你所需交互的字段数据.我们往往把这类文件放在model层. 2.view层,存放前端网页的. 3.controller层实现前端网页功能的,在这个层里面我们编写的方法称为action. www.lazyfitne

Professional C# 6 and .NET Core 1.0 - Chapter 41 ASP.NET MVC

What's In This Chapter? Features of ASP.NET MVC 6 Routing Creating Controllers Creating Views Validating User Inputs Using Filters Working with HTML and Tag Helpers Creating Data-Driven Web Applications Implementing Authentication and Authorization W

asp.net mvc 页面传值的方法总结

转自:http://msprogrammer.serviciipeweb.ro/2012/01/15/usual-methods-to-transfer-data-from-page-to-page-in-asp-net-mvc/ Usual Methods to transfer data from Page To Page in ASP.NET MVC Preamble: In ASP.NET ( like in PHP and other Web frameworks) there are

Asp.Net MVC中使用ACE模板之Jqgrid

第一次看到ACE模板,有种感动,有种相见恨晚的感觉,于是迅速来研究.它本身是基于bootstrap和jqueryui,但更nice,整合之后为后台开发节省了大量时间. 发现虽然不是完美,整体效果还是不错,特此分享给园友.这一节先讲其中的Jqgrid.按照国际惯例,先上两张图. 集成了button,form,treeview以及日历,时间轴.chart等控件,非常丰富.下面是Jqgrid在MVC中的使用. jqgrid的加载,排序,查找都是基于后台方法,不是在内存中完成,但也有一些小坑.下面一一道