从ASP.NET MVC中的URL获取字符串

Uma*_*oon 1 asp.net-mvc

使用控制器中的以下代码,我可以使用此url将类型的值传递为"rock":"http:// localhost:2414/Store/Browse?genre = rock"

public string Browse(string genre)
    {
        string message = HttpUtility.HtmlEncode("Store.Browse, Genre = "
    + genre);

        return message;
    }
Run Code Online (Sandbox Code Playgroud)

当URL为"http:// localhost:2414/Store/Browse/rock"时,我想传递相同的类型值

我怎样才能做到这一点?

Dar*_*rov 5

首先,您的控制器操作不应该像目前那样.所有控制器操作都应该返回一个ActionResult,而你不应该是HTML编码参数.这是观点的责任:

public ActionResult Browse(string genre)
{
    string message = string.Format("Store.Browse, Genre = {0}", genre);
    // the cast to object is necessary to use the proper overload of the method
    // using view model instead of a view location which is a string        
    return View((object)message); 
}
Run Code Online (Sandbox Code Playgroud)

然后在你的视图中显示和HTML编码如下:

<%= Html.DisplayForModel() %>
Run Code Online (Sandbox Code Playgroud)

现在回到你关于处理这样的网址的问题.您可以在以下位置定义以下路线Global.asax:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{genre}",
    new { controller = "Home", action = "Index", genre = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)

然后http://localhost:2414/Store/Browse/rock将调用作为参数传递BrowseStore控制器上的操作.rockgenre