Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are a few ways to pass parameters correctly from @Url.Action to a method:

  1. Query string parameters: add the parameters as part of the query string in the URL generated by @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
    ...
}
  1. Route parameters: add the parameters as part of the route definition in 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
    ...
}
  1. Form data: create a form in the view with input fields for the parameters. The method can then retrieve the values from the form using the 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
    ...
}