1 | initial version |
There are a few ways to pass parameters correctly from @Url.Action
to a method:
@Url.Action
. The method can then retrieve the values from the query string using the Request.QueryString
property.Example:
@Url.Action("MyAction", "MyController", new { id = 123, name = "John" })
public ActionResult MyAction(int id, string name)
{
// use id and name parameters
...
}
RouteConfig.cs
. The method can then retrieve the values from the route using the RouteData.Values
property.Example:
// RouteConfig.cs
routes.MapRoute(
name: "MyRoute",
url: "MyController/MyAction/{id}/{name}",
defaults: new { controller = "MyController", action = "MyAction", id = UrlParameter.Optional, name = UrlParameter.Optional }
);
// View
@Url.Action("MyAction", "MyController", new { id = 123, name = "John" })
// Controller
public ActionResult MyAction(int id, string name)
{
// use id and name parameters
...
}
Request.Form
property.Example:
// View
<form action="@Url.Action("MyAction", "MyController")" method="post">
<input type="text" name="id" value="123" />
<input type="text" name="name" value="John" />
<button type="submit">Submit</button>
</form>
// Controller
[HttpPost]
public ActionResult MyAction()
{
int id = int.Parse(Request.Form["id"]);
string name = Request.Form["name"];
// use id and name parameters
...
}