Discussion on the method of how to transmit multiple parameters to Action of Asp. net Mvc
- 2021-10-13 07:13:41
- OfStack
Recently, there is one need in work: the user queries the log file information, views the specific log information of one, and may also view the list of other log information on the date where the log is located.
To accomplish this, I intend to pass in two parameters in URL, one to record the time of this log and one to record the primary key of the log, ID, so I am ready to start with the route of Asp. net MVC.
In the Global. asax file, the default route is as follows.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // With parameters URL
new { controller = "Logon", action = "Logon", id = UrlParameter.Optional } // Default value of parameter
);
In this route, only one parameter can be passed in after Action, and multiple parameters cannot be passed in. Therefore, routing information needs to be added.
In the Global file, a new route is added, the route name is "Default1", and the code is as follows
// No. 1 1 Kinds of routing Pass two parameters through
routes.MapRoute("Default1",
"{controller}/{action}/{Parma1}/{Parma2}",
new { controller = "", action = "" },
new { });
For the above route, two parameters can be passed in.
Here, we create an TestController, add an Test. cshtml page, and write the code on TestController, as follows
public ActionResult Test(string date, string id)
{
ViewData["date"] = date;
ViewData["id"] = id;
return View();
}
Write the following code on the Test. cshtml page
The log time to query is: @ViewData["date"]<br />
Log to query ID Is: @ViewData["id"]<br />
Run the compiler and enter "http://localhost: 11507/Test/Test/2013-12-18/5" in the browser. The page appears as follows
The log time to query is: December 18, 2013
The log ID to query is: 5
Now there is another problem, which needs to pass in multiple parameters. What should I do? Of course, only the new route "Default2" is added. The code is as follows
// No. 1 2 Kinds of routing Pass multiple parameters, only get the first 2 All the data after the underline
routes.MapRoute("Default2",
"{controller}/{action}/{*id}",
new { controller = "", action = "" }
);
Run the compiler and enter "http://localhost: 11507/Test/Test/2013-12-18/5/xianrongbin" in the browser. The page appears as follows
The log time to query is:
The log ID to query is: 2013-12-18/5/xianrongbin
Here we can only get all the parameters behind Action, which we can analyze, for example, the log time is "2013-12-18", the log ID is "5", and the log operator is "xianrongbin".