ASP. Net MVC Controller and mvccontroller
The Controller is mainly responsible for responding to user input. The main concern is the application stream, the processing of input data, and the provision of relevant View output data.
- Inherited from: System. Web. Mvc. Controller
- A Controller can contain multiple actions. Each Action is a method and an ActionResult instance is returned.
- A Controller corresponds to a xxController. cs control file, which corresponds to a xx folder in the View. Generally, an Action corresponds to a View page.
Controller Action method parameters and return values
Parameters received by the Action method:
A. Receive parameters passed by the browser (get-two formats/post)
A1. receive FormCollection Request. Form
1. Obtain the data submitted by the Form one by one through Request. Form ["name "]
In the View
@Html.TextBoxFor(x => x.CusName, new { @class = "trade-timen", @id = "cusName" })<span class="wtps">* @Html.ValidationMessageFor(m => m.CusName)
Controller
[HttpPost]
public string UpdateCustomerInfo(FormCollection form)
{
return Request.Form["CusName"];;
}
Note: there must be a form element whose name attribute is CusName on The View Interface, because only data with name labels will be submitted when the form data is submitted.
2. Use FormCollection form to obtain the data submitted by the form one by one
[HttpPost]
public string UpdateCustomerInfo(FormCollection form) { return form["CusName"];
}
A2. receive Model
Obtain the data of the form element from the object at a time and set it to the attribute corresponding to the object.
/// <Summary>
/// Modify the customer
/// </Summary>
/// <Param name = "info"> </param>
/// <Returns> </returns>
[HttpPost]
Public ActionResult UpdateCustomer (CustomerInfo info)
{
String msg = string. Empty;
If (ModelState. IsValid)
{
Try
{
CustomerInfo model = CustomerInfo. Load (info. ID );
Model. CusCode = info. CusCode;
Model. CusName = info. CusName;
Model. Phone = info. Phone;
Model. Tel = info. Tel;
Model. Email = info. Email;
Model. Fax = info. Fax;
Model. Country = info. Country;
Model. Address = info. Address;
Model. CompanyName = info. CompanyName;
Model. BusssinessType = info. BusssinessType;
Model. Status = info. Status;
Model. Update ();
Msg = "customer modified successfully. ";
}
Catch (Exception ex)
{
Msg = "failed to modify customer! "+ Ex. Message;
ViewBag. Msg = string. Format (message, msg, false, "1 ");
}
ViewBag. Msg = string. Format (message, msg, true, "0 ");
}
Return View ();
}
Note: The attribute names of form elements must be the same as those of object objects!
Collapse all methods in the class: ctrl + m + o
Collapse all the code blocks in the class, including the class ctrl + m + l
B. Receive Get data, Request. QueryString
Get the url directly through the Request in the Request context object? The following parameters:
Browser Request Path:/User/UserList/1? Kjy = jp
Controller: Request. QueryString ["kjy"];
Return Value of the Action Method output:
B1.string: returns the response message string directly;
B2.ActionResult: return the result object of the controller.
(What will it contain? What can we do ?)
B3.JsonResult: returns a Json string.
Return Value of Action-ActionResult
Action specifies the view
Public ActionResult Index () {return View (); // by default, a View with the same name as the method is not returned for the parameter, that is, View Index is used. the cshtml path returns View ("OtherIndex") under the View directory corresponding to the current controller; // use OtherIndex. cshtml return View ("~ /Views/Home/Test. cshtml ");}
How does the Controller transmit data to the View?
How the Controller transfers the processed data to the view
ViewData/ViewBag/TempData/Model
Let's take a look at the example below.
Controller code:
Public ActionResult Index () {ViewBag. userName = "Xiao Li Fei Dao"; ViewData ["UserName"] = "Lu Xiaofeng"; TempData ["UserName"] = "Chu Liuxiang "; // temporary data User model = new User {UserName = "Xie Xiaofeng"}; return View (model); // This line of code is actually equivalent to ViewData. model = model}
View code:
@{ ViewBag.Title = "Index";}<div>@ViewBag.UserName </div><div>@ViewData["UserName"] </div><div>@TempData["UserName"] </div><div>@Model.UserName</div>
The Model is actually ViewData. Model.
You may think this is very obvious, and the result must be
Xiao Li, Fei Dao, Lu Xiaofeng, Chu Liuxiang, Xie Xiaofeng. However, I want to tell you that the result is not as you think, but will be shown as follows: Lu Xiaofeng, Lu Xiaofeng, Chu Liuxiang, Xie Xiaofeng why? Because ViewData and ViewBag are essentially of the ViewDataDictionary type and share data between them, they only provide different syntax operations. Therefore, "Lu Xiaofeng" covers the original value of "Xiao Fei Dao". TempData. We can see the name. It is only used for temporary storage, and once it is stored, it becomes invalid and will not be shared. Open Reflector, a sharp tool recommended by I keep vomiting blood. Let's take a look at the source code. We can see HomeController: Controller, public abstract class Controller: ControllerBase.
It is found that as long as an element is extracted from TempData, it will be removed immediately!
Model strongly typed Parameters
When the Action Method in the Controller finally calls the View to load the View, the data object is passed in.
return View(model);
View, which can be obtained through the Model attribute! And can be used directly without transformation!
Note: although the Model can be directly used without transformation, it cannot be intelligently prompted because the compiler cannot obtain its type during compilation! To solve this problem, we can specify the model type through code at the top of the attempt.
View Source Code:
When we try to add the @ model command
The current view inherits from the WebViewPage <T> strong-type view page class and specifies T as Student:
If the @ model command is not added, the current view inherits from the WebViewPage <T> strong view page class, but T becomes the dynamic
At this point, how can the Controller data be transmitted to the View? I only assigned a value to ViewData/ViewBag/TempData/in the Controller, or only passed the object to the View method.
Why can I directly call it in View? We know that the previous ASP. NET, aspx, and aspx. cs are an inheritance relationship. Subclass can directly call the attribute methods of the parent class. What is the relationship between View and Controller in ASP. net mvc?
Both View and Controller have ViewData/ViewBag/TempData objects. After assigning values to these objects in the Controller, the Controller assigns these values to the corresponding objects in the View.