【问题标题】:QueryString and RenderActionQueryString 和 RenderAction
【发布时间】:2012-01-05 12:37:37
【问题描述】:

当发送特定的查询字符串参数时,我正在我的 html 标记上设置一个类,现在我正在这样做(Razor 视图母版页):

@if (HttpContext.Current.Request.QueryString.AllKeys.Contains("Foo") && HttpContext.Current.Request.QueryString["Foo"] == "Bar") {
  //Do something when Foo=Bar (like http://server/route?Foo==Bar)
  <html class="bar-class">
}
else {
  //Normal html tag
  <html>
}

正常的请求可以正常工作,但是当我使用 RenderAction 调用页面时就不行了,比如

//Other view, the one requested by the user
@Html.RenderAction("Index", "Route", new {Foo="Bar"})

环顾四周后,我意识到只有一个实际的 HttpContext,这意味着 HttpContext.Current 指向第一个请求。那么 - 如何获取子请求的查询字符串数据?

谢谢! /维克多

【问题讨论】:

  • 您在new {Foo = "Bar" } 中缺少引用。

标签: c# razor query-string renderaction asp.net-mvc


【解决方案1】:

您可以使用string 作为您的Model,而不是使用查询字符串。

@model string
@if (!string.IsNullOrWhiteSpace(Model) && Model == "Bar") {
  //Do something when Foo=Bar (like http://server/route?Foo==Bar)
  <html class="bar-class">
}
else {
  //Normal html tag
  <html>
}

public ActionResult Route(string foo){
  return View(foo);
}

【讨论】:

  • 问题是我需要这个通用的 - 我将在布局中使用 每个 请求,并且模型需要由实际视图决定。所以我真的需要访问原始查询字符串(或类似的)......也许过滤器可能是一个想法,但我不知道如何......
【解决方案2】:

至少现在我通过使用 TempData 字典并在使用后删除值解决了这个问题,但我仍然对更好的解决方案感兴趣。似乎应该有一种方法可以让路由数据通过...

/维克多

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2010-10-11
    相关资源
    最近更新 更多