MVC中处理Json和JS中处理Json对象

MVC中处理Json和JS中处理Json对象

mvc已经很好封装了JSon,不用js那样复杂
前台:
<script>
$.ajax({
url: "/Home/Test",
dataType: "json",
cache: false,
data: null,
type: "POST",
success: function (data) {
alert(data.Data.Name);
}
});

后台:
public JsonResult Test()
{
JsonResult json = new JsonResult()
{
Data = new
{
Name = "张三",
Sex = "男"
}
};
return json;
}


前台:
$.ajax({
url: "/Home/TestList",
dataType: "json",
cache: false,
data: null,
type: "POST",
success: function (data) {
var msg = "";
for (var i = 0, length = data.Data.length; i < length; i++) {
msg += "<DiV>Name:" + data.Data[i].Name + ",Email:" +

data.Data[i].Email + "</div>";

}
$("#msg2").html(msg);
}
});

 

第二种也可以这样写:
第二种列表的方法,也可以这样来实现更加简单:

 

public JsonResult TestList()
{
List<User> userList = new List<User>
{
new User{Username="zhangsan",Email="zhangsan@sina.com"},
new User{Username="Lisi",Email="Lisi@sina.com"}
};
return Json(userList);

//return Json(userList, JsonRequestBehavior.AllowGet);//前台AJAX如果是GET用这句

}
$.ajax({
url: "/Home/TestList",
dataType: "json",
cache: false,
data: null,
type: "POST",
success: function (data) {
var msg = "<table border=1><thead><tr><td>Name</td><td>Email</td>
</tr></thead><tbody>";
for (var i = 0, length = data.length; i < length; i++) {
msg += "<tr><td>" + data[i].Name + "</td><td>"
+ data[i].Email + "</td></tr>";
}
msg += "</body></table>";
$("#msg2").html(msg);
}
});
后台:
public JsonResult TestList()
{
List<User> userList = new List<User>
{
new User{Username="zhangsan",Email="zhangsan@sina.com"},
new User{Username="Lisi",Email="Lisi@sina.com"}
};
JsonResult json = new JsonResult()
{
Data = userList
};
return json;
}

 

另外:使用json比用string返回数据更好

以前的程序:

ViewData["msg"] = "{result:true,FileName:\"" + new FileInfo(Request.Files[0].FileName).Name +
                  "\",FileUrl:\"" + fileurl.Replace("\"", "") + "\"}";
重构之后的程序:
 JsonResult j = Json(new
                 {
                     Result = true,
                     FileName = new FileInfo(Request.Files[0].FileName).Name,
                     FileUrl = fileurl.Replace("\"", "")
                 });
                ViewData["msg"] = j.Data.ToString();

posted @ 2016-06-24 15:57  那就让我这样吧  阅读(193)  评论(0编辑  收藏  举报