Ask Your Question
1

How to pass parameter correctly from @Url.Action to method?

asked 2021-08-10 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-03-17 12:00:00 +0000

qstack gravatar image

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
    ...
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-10 11:00:00 +0000

Seen: 15 times

Last updated: Mar 17 '22