The way the Controller passes values to the view in ASP.NET MVC :
- ViewBag、ViewData、TempData
- passing a single value
- Json
- anonymous type
- ExpandoObject
- Cookie
- ViewModel (pass a Model object to a normal View page, pass a Model object to a strongly typed page, use a ViewModel object to solve all problems)
How to pass values from view to Controller in ASP.NET MVC
- QueryString
- RouteData
- Model Binding (form, use the variable with the same name as the Action parameter to pass)
- Cookie
The role of ViewBag in MVC is the transfer of data. Starting with MVC3, view data can be accessed through the ViewBag property. In MVC2, ViewData is used. The use of ViewData is preserved in MVC3. ViewBag is a dynamic type (dynamic), ViewData is a word typical (Dictionary).
The difference between ViewBag and ViewData in MVC3:
ViewBag is no longer a key-value pair structure of a dictionary, but a dynamic dynamic type. It will be resolved dynamically when the program is executed.
So there is no need for type conversion when getting its data in the view
ViewData | ViewBag |
It is a collection of Key/Value dictionaries | it is a dynamic type object |
Available from Asp.net MVC 1 | ASP.NET MVC3 only |
Based on Asp.net 3.5 framework | Based on Asp.net 4.0 and .net framework |
ViewData is faster than ViewBag | ViewBag is slower than ViewData |
When querying data in ViewPage, you need to convert the appropriate type | No need for type conversion when querying data in ViewPage |
There is some type conversion code | better readability |
How the View passes data to the Controller
QueryString
Code in View:
<div> <button id="btn">提交</button> </div> <script> $(function () { $('#btn').click(function () { //url is not case sensitive location.href = "/home/getvalue?method=querystring"; }); }); </script>
Code in Controller:
public void GetValue() { //Request attribute can be used to get querystring, form and cookie values var querystring = Request["method"]; }
Using querystring to pass to the background belongs to the get method in the http protocol, that is, the data will be exposed in the url, the security is not high (the sent data can be seen through the browser history), and the amount of transmitted data is limited in size.
The address in the browser address bar after clicking the submit button:http://localhost:57625/home/getvalue?method=querystring。程序执行结果如下:
RouteData
Routing allows us to write a more readable url and use routing to pass data. First, configure the appropriate routing:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}" );
The front-end code only needs to change location.href
the value to the url that matches the route. In this example, it "/home/getvalue/100"
is the code in the Controller:
public void GetValue() { var value = RouteData.Values["id"]; }
The obtained value is of type object:
Another way to get routing parameters is to set a parameter for Action that is the same as the parameter name specified in the routing template (case-insensitive) . The code is as follows:
public void GetValue(int id) { }
Note that not only the routing data is obtained here, but also the data type is automatically converted to int type:
ModelBinding
1. Form
The form form is a common way to send data to the backend, but when submitting data, only the value of the input, textarea, and select tags with the name attribute in the form is submitted . Code in View:
<form action="/home/getvalue" method="post"> <input type="text" name="username" /> <input type="text" name="age" /> <input type="submit" name="button" value="提交" /> </form>
Code in Controller:
public void GetValue() { var name = Request["username"]; var age = Request["age"]; var btn = Request["button"]; }
The obtained data is all string type:
Now we create a class corresponding to the form form:
public class User { public string UserName { set; get; } public int Age { set; get; } }
The code to modify the Action is as follows:
public void GetValue(User user) { }
Then run the program, you can see that MVC maps the data in the form to the attribute value of the User class instance, and performs the corresponding data type conversion.
2. Use a variable with the same name as the Action parameter to pass
Code in View:
<button id="btn">pass data</button> <script> $(function () { $('#btn').click(function () { $.ajax({ 'type': 'post', 'url': '/home/getdata', //The data passed can also be serialized json format data //For example, using the form form above to submit data, you can use the serialize() method in jquery to serialize the form and submit it after //data:$('#form').serialize() 'data': { username: 'Xue Feihong', age: '24' }, error: function (message) { alert('error!'); } }); }) }) </script>
Code in Controller:
public void GetData(string username, int age) { }
The corresponding parameter value is successfully obtained in the Action, and the data type is also converted according to the type of the parameter in the Action.
The jquery.cookie plugin is referenced here to perform cookie operations
<body> <button id="btn">提交</button> <script> $(function () { // write value to cookie $.cookie('key', 'jscookie'); $('#btn').click(function () { location.href = "/home/getvalue"; }); }) </script> </body>
public void GetValue() { var cookie = Request["key"]; }
Controller passes values to View
passing a single value
public ActionResult Index() { //Note that the passed value cannot be of string type, otherwise the View(string viewName) method will be executed and the correct result will not be obtained return View(100); }
<body> <p>@Model</p> </body>
Json
public ActionResult Index() { return View(); } public JsonResult SendData() { return Json(new { UserName = "Xue Feihong", 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">Get data</button> <script> $(function () { $('#btn').click(function () { $.ajax({ 'url': '/home/senddata', 'type': 'post', success: function (data) { $('#message').html('Username:' + data.UserName + "<br/>Age:" + data.Age); }, error: function (message) { alert('error:' + message.statusText); } }); }); }); </script> </body> </html>
anonymous type
public ActionResult Index() { //Use anonymous class to pass data to View return View(new { UserName = "Xue Feihong", Age = 24 }); }
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> </head> <body> <p>Username: @Model.UserName</p> <p>Age: @Model.Age</p> </body> </html>
Because the type name of an anonymous type is generated by the compiler and cannot be used at the source level. Therefore, if you directly use anonymous types to pass data to the View, the properties in the anonymous types cannot be accessed on the front page. Executing the above code program will give an error:
For the above problem, use Newtonsoft to convert the anonymous type to json format to solve the problem.
Use NuGet to import the Newtonsoft.Json package, and then modify the code as follows:
public ActionResult Index() { string json = JsonConvert.SerializeObject(new { UserName = "Xue Feihong", Age = 24 }); //You can also directly serialize strings in JSON format //dynamic jsonObj = JsonConvert.DeserializeObject("{ UserName : \"雪飞鸿\", Age : 24 }"); dynamic jsonObj = JsonConvert.DeserializeObject(json); return View(jsonObj); }
ExpandoObject
As mentioned above, it is not feasible to use anonymous types to pass data to the View directly. You can use ExpandoObject type objects instead of anonymous types
public ActionResult Index() { dynamic user = new ExpandoObject(); user.UserName = "Xue Feihong"; user.Age = 24; return View(user); }
ViewBag、ViewData、TempData
public ActionResult Index() { ViewBag.Title = "Data Transfer"; ViewData["key"] = "Pass Data"; //By default, the data in TempData can only be used once 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>
ViewModel
Pass data to frontend via viewmodel
// view model 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); }
@* Set the page to be strongly typed *@ @model DataTransfer.Controllers.User @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> </head> <body> <p>Username: @Model.UserName</p> <p>Age: @Model.Age</p> </body> </html>
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>