ASP.NET MVC - passing parameters to the controller

后端 未结 10 1292
小蘑菇
小蘑菇 2020-11-28 23:36

I have a controller with an action method as follows:

public class InventoryController : Controller
{
    public ActionResult ViewStockNext(int firstItem)
           


        
相关标签:
10条回答
  • 2020-11-29 00:00

    The reason for the special treatment of "id" is that it is added to the default route mapping. To change this, go to Global.asax.cs, and you will find the following line:

    routes.MapRoute ("Default", "{controller}/{action}/{id}", 
                     new { controller = "Home", action = "Index", id = "" });
    

    Change it to:

    routes.MapRoute ("Default", "{controller}/{action}", 
                     new { controller = "Home", action = "Index" });
    
    0 讨论(0)
  • 2020-11-29 00:01

    Using the ASP.NET Core Tag Helper feature:

    <a asp-controller="Home" asp-action="SetLanguage" asp-route-yourparam1="@item.Value">@item.Text</a>
    
    0 讨论(0)
  • 2020-11-29 00:02

    There is another way to accomplish that (described in more details in Stephen Walther's Pager example

    Essentially, you create a link in the view:

    Html.ActionLink("Next page", "Index", routeData)
    

    In routeData you can specify name/value pairs (e.g., routeData["page"] = 5), and in the controller Index function corresponding parameters receive the value. That is,

    public ViewResult Index(int? page)
    

    will have page passed as 5. I have to admit, it's quite unusual that string ("page") automagically becomes a variable - but that's how MVC works in other languages as well...

    0 讨论(0)
  • 2020-11-29 00:03

    Or, you could try changing the parameter type to string, then convert the string to an integer in the method. I am new to MVC, but I believe you need nullable objects in your parameter list, how else will the controller indicate that no such parameter was provided? So...

    public ActionResult ViewNextItem(string id)...
    
    0 讨论(0)
  • 2020-11-29 00:09

    Headspring created a nice library that allows you to add aliases to your parameters in attributes on the action. This looks like this:

    [ParameterAlias("firstItem", "id", Order = 3)]
    public ActionResult ViewStockNext(int firstItem)
    {
        // Do some stuff
    }
    

    With this you don't have to alter your routing just to handle a different parameter name. The library also supports applying it multiple times so you can map several parameter spellings (handy when refactoring without breaking your public interface).

    You can get it from Nuget and read Jeffrey Palermo's article on it here

    0 讨论(0)
  • 2020-11-29 00:10

    public ActionResult ViewNextItem(int? id) makes the id integer a nullable type, no need for string<->int conversions.

    0 讨论(0)
提交回复
热议问题