MVC路由后如何获取querystring值
How to get querystring value after MVC routing
我猜我的方法是错误的,这就是为什么我的研究收效甚微
我的网站使用了查询字符串,在我的 HtmlHelper class 中,我可以使用以下代码获取查询字符串
当您启动 MVC4 时,defulat 路由允许您将 ID 作为查询字符串传递。路由引擎 'converts' 这从一个查询字符串变成 URL 的一部分
我该如何查询这个值?
public static MvcHtmlString ActionLinkWithQueryString(this HtmlHelper helper, string linkText, string action, string controllerName, object routeValues)
{
var queryString = helper.ViewContext.HttpContext.Request.QueryString;
...
以上工作正常。
不过,我现在正在使用路由引擎。当你第一次开始使用 MVC 时,你会得到为你设置的 ID 参数,当你执行类似于 www.mysite.com/?id=HelloWorld
的搜索时,路由引擎 'converts' 或 'translates' 将其转换为 URL ,例如 www.mysite.com/HelloWorld
问题是,我仍然需要获取该值 - HelloWorld 值。
使用上面的代码总是returns一个空列表,因为没有查询字符串!
我知道我可以读取 URL,用正斜杠分割,然后从数组中取出项目,但我希望有更优雅的方法。
真正的原因是分页。发生的事情是我的 URL 是 www.mysite.com/products/shoes/12
然后我单击下一页,它丢失了值,显示 www.mysite.com/products/10
(其中 10 是起始索引)。显然我需要 URL 为 www.mysite.com/products/10/shoes/12
如何从 URL 中获取值 HelloWorld(ID 参数)?
您可以从路由值中获取:
object id = helper.ViewContext.RouteData.Values["id"];
我猜我的方法是错误的,这就是为什么我的研究收效甚微
我的网站使用了查询字符串,在我的 HtmlHelper class 中,我可以使用以下代码获取查询字符串
当您启动 MVC4 时,defulat 路由允许您将 ID 作为查询字符串传递。路由引擎 'converts' 这从一个查询字符串变成 URL 的一部分 我该如何查询这个值?
public static MvcHtmlString ActionLinkWithQueryString(this HtmlHelper helper, string linkText, string action, string controllerName, object routeValues)
{
var queryString = helper.ViewContext.HttpContext.Request.QueryString;
...
以上工作正常。
不过,我现在正在使用路由引擎。当你第一次开始使用 MVC 时,你会得到为你设置的 ID 参数,当你执行类似于 www.mysite.com/?id=HelloWorld
的搜索时,路由引擎 'converts' 或 'translates' 将其转换为 URL ,例如 www.mysite.com/HelloWorld
问题是,我仍然需要获取该值 - HelloWorld 值。
使用上面的代码总是returns一个空列表,因为没有查询字符串!
我知道我可以读取 URL,用正斜杠分割,然后从数组中取出项目,但我希望有更优雅的方法。
真正的原因是分页。发生的事情是我的 URL 是 www.mysite.com/products/shoes/12
然后我单击下一页,它丢失了值,显示 www.mysite.com/products/10
(其中 10 是起始索引)。显然我需要 URL 为 www.mysite.com/products/10/shoes/12
如何从 URL 中获取值 HelloWorld(ID 参数)?
您可以从路由值中获取:
object id = helper.ViewContext.RouteData.Values["id"];