The way the controller and view pass values to each other in ASP.NET MVC

  The way the Controller passes values ​​to the view in ASP.NET MVC :

  1. ViewBag、ViewData、TempData
  2. passing a single value
  3. Json
  4. anonymous type
  5. ExpandoObject
  6. Cookie
  7. 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

  1. QueryString
  2. RouteData
  3. Model Binding (form, use the variable with the same name as the Action parameter to pass)
  4. 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:

copy code
<div>
    <button id="btn">提交</button>
</div>
<script>
    $(function () {
        $('#btn').click(function () {
            //url is not case sensitive
            location.href = "/home/getvalue?method=querystring";
        });
    });
</script>
copy code

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.hrefthe 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:

Both querystring and routing are transmitted through url. If the data contains Chinese, the Encode operation should be performed. In addition, the length of the url is limited, and the use of url cannot pass too much data. The url passing parameter belongs to the Get request in the Http protocol. To send a large amount of data, you can use the Post request.

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:

copy code
public void GetValue()
{
    var name = Request["username"];
    var age = Request["age"];
    var btn = Request["button"];
}
copy code

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:

copy code
<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>
copy code

 

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.

 
Model binding is reflected in the parameters of the same name extracted from the current request and bound to the target Action method. For such an Action, if it is a Post request, MVC will try to convert the Form ( note that the Form here does not refer to the <form> form in html, but the way the Post method sends data. If we use the developer tools to view the Post method The sent request information, you will see the value in the Form Data column) is assigned to the Action parameter. If it is a get request, MVC will try to assign the value of QueryString to the Action parameter.
 

Cookie

The jquery.cookie plugin is referenced here to perform cookie operations

copy code
<body>
    <button id="btn">提交</button>
    <script>
        $(function () {
            // write value to cookie
            $.cookie('key', 'jscookie');

            $('#btn').click(function () {
                location.href = "/home/getvalue";
            });
        })
    </script>
</body>
copy code
public void GetValue()
{
    var cookie = Request["key"];
}

 

 

Controller passes values ​​to View

passing a single value

copy code
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);
}
copy code
<body>
 <p>@Model</p>
</body>
The program execution result is as follows:

Json

copy code
public ActionResult Index()
{
    return View();
}

public JsonResult SendData()
{
    return Json(new { UserName = "Xue Feihong", Age = 24 });
}
copy code
copy code
<!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>
copy code
The program execution result is as follows:

anonymous type

public ActionResult Index()
{
    //Use anonymous class to pass data to View
    return View(new { UserName = "Xue Feihong", Age = 24 });
}
copy code
<!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>
copy code

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:

copy code
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);
}
copy code
The program execution result is as follows:

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

copy code
public ActionResult Index()
{
    dynamic user = new ExpandoObject();
    user.UserName = "Xue Feihong";
    user.Age = 24;
    return View(user);
}
copy code
The program execution result is as follows:

ViewBag、ViewData、TempData

copy code
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();
}
copy code
copy code
<!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>
copy code
The program execution result is as follows:

ViewModel

Pass data to frontend via viewmodel

copy code
// 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);
}
copy code
copy code
@* 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>
copy code
The program execution result is as follows:

Cookie

public ActionResult Index()
{
    Response.SetCookie(new HttpCookie("key", "cookie"));
    return View();
}
copy code
<body>
    <p id="message"></p>
    <script>
        $(function () {
            var message = $.cookie('key');
            $('#message').text(message);
        })
    </script>
</body>
copy code
The program execution result is as follows:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324648075&siteId=291194637