Asp.Net MVC以JSON传值扩展方法
Asp.Net在客户端和服务器端,以JSON形式相互传值,可写扩展方法,用到的类型如下:
DataContractJsonSerializer类:
该类在System.Runtime.Serialization.Json命名空间下,是将对象序列化为JavaScript对象表示法(Json),并将Json数据反序列化为对象。
以Asp.Net MVC为例:
扩展方法如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Runtime.Serialization.Json;
namespace System.Web.Mvc
{
public static class MyFormCollention
{
/// <summary>
/// 生成Json格式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string ToJsonStr<T>(T obj)
{
DataContractJsonSerializerjson = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, obj);
string szJson = System.Text.Encoding.UTF8.GetString(stream.ToArray());
return szJson;
}
}
/// <summary>
/// 将JSON 字符转换为对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="str"></param>
/// <returns></returns>
public static T ToJsonObject<T>(this string str)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStreamms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str)))
{
DataContractJsonSerializerserializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
}
}
网页客户端,View的Home文件夹(View视图):
<script>
var Person={
Name:"liu",
Age:"20",
}
functionReposeJson() {
$.ajax({
type:"Get",
url:"@Url.Action("SetJson","Home")?json="+JSON.stringify(Person),
dataType: "Json",
success: function (data)
{
alert(data.Name);
alert(data.Age);
}
})
}
</script>
<h3>We suggest the following:</h3>
<olclass="round">
<liclass="one">
<ahref="#"onclick="ReposeJson()">Learn more…</a>
</li>
</ol>
控制器调用:
public class HomeController : Controller
{
[HttpGet]
public string SetJson(string json)
{
Person boy = MyFormCollention.ToJsonObject<Person>(json);
Person girl = new Person();
girl.Age = "19";
girl.Name = "wang";
json = MyFormCollention.ToJsonStr<Person>(girl);
return json;
}
}
实体类:
public class Person {
public string Name{set;get;}
public string Age { set; get; }
}