65.9K
CodeProject 正在变化。 阅读更多。
Home

带有Jquery MVC2和模型绑定器的Json

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013 年 10 月 11 日

CPOL

2分钟阅读

viewsIcon

9886

大家好,在这篇文章中,我将展示 Json 的魔力,以及我们知道 MVC3 默认拥有的 Model Binder。 这是一个简单的

大家好,

在这篇文章中,我将展示 Json 的魔力,以及我们知道 MVC3 默认拥有的 Model Binder。这是一个简单的例子,但我相信你们会大量使用它。

对于这个例子,你需要添加由 Douglas Crockford 创建的库 Json2

以及这些引用:用于 Model Binder 的 System.Reflection 和 System.Web.Script.Serialization。

 

视图:(Jquery 代码)

<input type="button" value="Come on Json" onclick="javascript:ComeOnJson()" id="jsonResult" />

<script language="javascript" type="text/javascript">

vardata = [{"lastName": "Orue", "firstName": "Esteban", "phones": [{ "type": "Mobile", "number": "(011) 4121-2121" },{ "type": "Home", "number": "(011) 4123-4567"}]

},

{ "firstName": "Sensei", "lastName": "Miyagi", "phones": [{ "type": "Mobile", "number": "(011) 4121-7777" },

{ "type": "Home", "number": "(011) 4121-9999"}]

}];

 

functionComeOnJson(){

alert(JSON.stringify(data));

$.ajax({

url
'/Home/CollectJsonData',

data: JSON.stringify(data),

type'POST',contentType'application/json; charset=utf-8',

dataType'json',

 successfunction(result) {

alert(result);

},

errorfunction () {

alert("error");

}

});

}

</script>

 

控制器 (Controller)

[HttpPost]

public ActionResultCollectJsonData(列表<人员> person)

{

returnJson(data: person[0].firstName.ToString());

}

模型

public 人员

{

public 字符串firstName {get; set; }

public 字符串lastName {get; set; }

public 列表<电话> phones {get; set; }

}

public 电话

{

public 字符串type {get; set; } public 字符串number {get; set; }

}

Model Binder

usingSystem.Reflection;

usingSystem.Web.Script.Serialization;

 

public JsonModelBinder : DefaultModelBinder

{

public override objectBindModel(ControllerContextcontrollerContext,ModelBindingContextbindingContext)

{

if(!IsJSONRequest(controllerContext))

{

return base.BindModel(controllerContext, bindingContext);

}

// 获取已发布的 JSON 数据

varrequest = controllerContext.HttpContext.Request;

varjsonStringData =new StreamReader(request.InputStream).ReadToEnd();

 

return new JavaScriptSerializer()

.Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);

}私有的 static boolIsJSONRequest(ControllerContextcontrollerContext)

{

varcontentType = controllerContext.HttpContext.Request.ContentType;returncontentType.Contains("application/json");

}

}

public static JavaScriptSerializerExt

{

public static objectDeserialize(this JavaScriptSerializerserializer,字符串input,类型objType)

{

vardeserializerMethod = serializer.GetType().GetMethod("Deserialize", BindingFlags.NonPublic |BindingFlags.Static);

returndeserializerMethod.Invoke(serializer,new object[] { serializer, input, objType, serializer.RecursionLimit });

}

}

Global.asax

受保护的 voidApplication_Start()

{

//AreaRegistration.RegisterAllAreas();

ModelBinders.Binders.DefaultBinder =new JsonModelBinder();

RegisterRoutes(RouteTable.Routes);

}

 

希望对你们有帮助!

祝你好运!

© . All rights reserved.