使用ASP.NET MVC做開發(fā)時,經(jīng)常需要在頁面(View)和控制器(Controller)之間傳遞數(shù)據(jù),那么都有哪些數(shù)據(jù)傳遞的方式呢?
本文對于View向Controller中傳值共列舉了以下幾種方式:
- QueryString
- RouteData
- Model Binding
- Form
- 使用和Action參數(shù)同名的變量進行傳遞
- Cookie
對于Controller向View中傳值則列舉了以下幾種方式:
- 單個值的傳遞
- Json
- 匿名類型
- ExpandoObject
- ViewBag、ViewData、TempData
- ViewModel
- Cookie
View向Controller中傳遞數(shù)據(jù)的方式
<p id='querystring'>QueryString</p>
View中代碼:
<div>
<button id="btn">提交</button>
</div>
<script>
$(function () {
$('#btn').click(function () {
//url不區(qū)分大小寫
location.href = "/home/getvalue?method=querystring";
});
});
</script>
Controller中代碼:
public void GetValue()
{
//Request屬性可用來獲取querystring,form表單以及cookie中的值
var querystring = Request["method"];
}
使用querystring向后臺傳遞屬于http協(xié)議中的get方式,即數(shù)據(jù)會暴露在url中,安全性不高(可通過瀏覽器歷史記錄看到發(fā)送的數(shù)據(jù))且傳遞的數(shù)據(jù)量有大小限制。
點擊提交按鈕后瀏覽器地址欄中的地址:http://localhost:57625/home/getvalue?method=querystring
<p id='routedata'>RouteData</p>
路由可以讓我們寫出可讀性較高的url,使用路由傳遞數(shù)據(jù),首先要配置合適的路由:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}"
);
前端代碼只需要將location.href的值改為和路由匹配的url即可,本示例中為"/home/getvalue/100"
Controller中的代碼:
public void GetValue()
{
var value = RouteData.Values["id"];
}
獲取的值是object類型
獲取路由參數(shù)的另外一種方式是給Action設置一個和路由模板中指定的參數(shù)名一致(不區(qū)分大小寫)的參數(shù)即可,代碼如下:
public void GetValue(int id)
{
}
注意:這里不僅獲取了路由數(shù)據(jù),而且自動將數(shù)據(jù)類型轉換為int類型
querystring和路由均是通過url進行數(shù)據(jù)的傳遞,若數(shù)據(jù)中包含中文應進行Encode操作。此外,url的長度是有限制的,使用url不可傳遞過多的數(shù)據(jù)。url傳遞參數(shù)屬于Http協(xié)議中的Get請求,若要發(fā)送大量數(shù)據(jù)可以使用Post請求。
<p id='modelbinding'>ModelBinding</p>
<p id='form'>1. Form</p>
form表單形式是常見的向后端發(fā)送數(shù)據(jù)的方式,但是在提交數(shù)據(jù)是只會提交form表單內(nèi)部具有name屬性的input,textarea,select標簽的value值。
View中的代碼:
<form action="/home/getvalue" method="post">
<input type="text" name="username" />
<input type="text" name="age" />
<input type="submit" name="button" value="提交" />
</form>
Controller中的代碼:
public void GetValue()
{
var name = Request["username"];
var age = Request["age"];
var btn = Request["button"];
}
獲取到的數(shù)據(jù)均為string類型
現(xiàn)在我們創(chuàng)建一個和form表單對應的類:
public class User
{
public string UserName { set; get; }
public int Age { set; get; }
}
修改Action的代碼如下:
public void GetValue(User user)
{
}
然后運行程序,可以看到MVC以將表單中的數(shù)據(jù)映射為User類實例的屬性值,且進行了相應的數(shù)據(jù)類型的轉換。
<p id='action'>2. 使用和Action參數(shù)同名的變量進行傳遞</p>
View中的代碼:
<button id="btn">傳遞數(shù)據(jù)</button>
<script>
$(function () {
$('#btn').click(function () {
$.ajax({
'type': 'post', 'url': '/home/getdata',
//傳遞的數(shù)據(jù)也可以是序列化之后的json格式數(shù)據(jù)
//如,上面使用form表單提交數(shù)據(jù)就可以使用jquery中的serialize()方法將表單進行序列化之后在提交
//data:$('#form').serialize()
'data': { username: '雪飛鴻', age: '24' },
error: function (message) {
alert('error!');
}
});
})
})
</script>
Controller中的代碼:
public void GetData(string username, int age)
{
}
在Action中成功獲取到了對應的參數(shù)值,且數(shù)據(jù)類型也根據(jù)Action中參數(shù)的類型進行了相應的轉換。
Model綁定體現(xiàn)在從當前請求提取相應的數(shù)據(jù)綁定到目標Action方法的同名參數(shù)(不區(qū)分大小寫)中。對于這樣的一個Action,如果是Post請求,MVC會嘗試將Form(注意,這里的Form不是指html中的<form>表單,而是Post方法發(fā)送數(shù)據(jù)的方式,若我們使用開發(fā)者工具查看Post方式發(fā)送的請求信息,會看到Form Data一欄)中的值賦值到Action參數(shù)中,如果是get請求,MVC會嘗試將QueryString的值賦值到Action參數(shù)中。
<p id='cookie'>Cookie</p>
這里引用jquery.cookie插件來進行cookie的操作
<body>
<button id="btn">提交</button>
<script>
$(function () {
//向cookie中寫入值
$.cookie('key', 'jscookie');
$('#btn').click(function () {
location.href = "/home/getvalue";
});
})
</script>
</body>
public void GetValue()
{
var cookie = Request["key"];
}
Controller向View中傳值
<p id='singlevalue'>單個值的傳遞</p>
public ActionResult Index()
{
//注意,傳遞的值不能是string類型,否則會執(zhí)行View(string viewName)方法而導致得不到正確結果
return View(100);
}
<body>
<p>@Model</p>
</body>
<p id='json'>Json</p>
public ActionResult Index()
{
return View();
}
public JsonResult SendData()
{
return Json(new { UserName = "雪飛鴻", Age = 24 });
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/scripts/jquery-1.10.2.min.js"></script>
</head>
<body>
<p id="message"></p>
<button id="btn">獲取數(shù)據(jù)</button>
<script>
$(function () {
$('#btn').click(function () {
$.ajax({
'url': '/home/senddata', 'type': 'post',
success: function (data) {
$('#message').html('用戶名:' + data.UserName + "<br/>年齡:" + data.Age);
},
error: function (message) {
alert('error:' + message.statusText);
}
});
});
});
</script>
</body>
</html>
<p id='anonymous'>匿名類型</p>
public ActionResult Index()
{
//使用匿名類向View中傳遞數(shù)據(jù)
return View(new { UserName = "雪飛鴻", Age = 24 });
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<p>用戶名:@Model.UserName</p>
<p>年齡:@Model.Age</p>
</body>
</html>
因為匿名類型的類型名由編譯器生成,并且不能在源代碼級使用。所以,直接使用匿名類型向View中傳遞數(shù)據(jù),在前臺頁面是無法訪問到匿名類型中的屬性的。執(zhí)行上面代碼程序會出現(xiàn)錯誤:
針對上述問題,使用Newtonsoft將匿名類型轉換為json格式即可解決該問題。
使用NuGet引入Newtonsoft.Json包,然后修改代碼如下:
public ActionResult Index()
{
string json = JsonConvert.SerializeObject(new { UserName = "雪飛鴻", Age = 24 });
//也可以直接序列化JSON格式的字符串
//dynamic jsonObj = JsonConvert.DeserializeObject("{ UserName : \"雪飛鴻\", Age : 24 }");
dynamic jsonObj = JsonConvert.DeserializeObject(json);
return View(jsonObj);
}
<p id='expandoObject'>ExpandoObject</p>
上面提到,直接使用匿名類型向View中傳遞數(shù)據(jù)是行不通的,可以使用ExpandoObject類型對象來替代匿名類型
public ActionResult Index()
{
dynamic user = new ExpandoObject();
user.UserName = "雪飛鴻";
user.Age = 24;
return View(user);
}
<p id='viewdata'>ViewBag、ViewData、TempData</p>
public ActionResult Index()
{
ViewBag.Title = "數(shù)據(jù)傳遞";
ViewData["key"] = "傳遞數(shù)據(jù)";
//默認情況下TempData中的數(shù)據(jù)只能使用一次
TempData["temp"] = "tempdata";
return View();
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<p>@ViewData["key"]</p>
<p>@TempData["temp"]</p>
</body>
</html>
<p id="viewmodel">ViewModel</p>
通過視圖模型將數(shù)據(jù)傳遞到前端
//視圖模型
public class User
{
public string UserName { set; get; }
public int Age { set; get; }
}
//Action
public ActionResult Index()
{
User user = new User() { UserName = "雪飛鴻", Age = 24 };
return View(user);
}
@* 設置頁面為強類型頁面 *@
@model DataTransfer.Controllers.User
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<p>用戶名:@Model.UserName</p>
<p>年齡:@Model.Age</p>
</body>
</html>
<p id="cookie2">Cookie</p>
public ActionResult Index()
{
Response.SetCookie(new HttpCookie("key", "cookie"));
return View();
}
<body>
<p id="message"></p>
<script>
$(function () {
var message = $.cookie('key');
$('#message').text(message);
})
</script>
</body>