【问题标题】:Getting a string from URL in ASP.NET MVC从 ASP.NET MVC 中的 URL 获取字符串
【发布时间】:2011-01-30 19:47:40
【问题描述】:

使用控制器中的以下代码,我可以通过以下网址将流派的值传递为“rock”:“http://localhost:2414/Store/Browse?genre=rock”

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

        return message;
    }

当 URL 为“http://localhost:2414/Store/Browse/rock”时,我想传递相同的流派值

我该怎么做?

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

首先,您的控制器操作不应该像现在这样。所有的控制器动作都应该返回一个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); 
}

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

<%= Html.DisplayForModel() %>

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

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

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

【讨论】:

  • 'id' 应该是路由默认值中的 'genre'。
【解决方案2】:

为了他人的利益,我想更正上述答案之一;

“首先你的控制器动作不应该像现在这样。所有控制器动作都应该返回一个 ActionResult...”

控制器操作应根据您返回的内容返回最具体的类型。例如。如果要返回 Partial View,则使用 PartialViewResult,或者如果要返回 Json,则返回 JsonResult。返回最具体的类型始终是最佳实践,这样单元测试会更准确。

P.S 控制器动作也可以返回,字符串,布尔值等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    相关资源
    最近更新 更多