检测视图中的路由值
是否可以在视图中检测路由值?
例如 /pages/create/1
我想检查 1 是否存在?
基本上,我想根据这个值渲染不同的部分视图,尽管我相当确定这可能不是实现我想要实现的目标的最佳方法。
顺便说一句,我是否可以根据控制器内的值来更改视图中呈现的部分视图,而不是执行上述操作?
Is it possible to detect a route value in a view?
Such as /pages/create/1
and I want to check to see if 1 is there?
Basically, I want to render a different partial view based on this value though I'm fairly sure this is probably not the best way to go about what I'm trying to achieve.
On a side note, instead of doing the above is it possible for me to be able to change what partial views are rendered in a view based on a value from within my controller?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以通过
ViewPage.ViewContext.RouteData
检查RouteData
对象。然后使用类似的方法检查值。如果您发现想要在控制器中检查这些值,则可以使用 ControllerBase.ControllerContext.RouteData 访问它们。类似的情况也适用于动作过滤器等。
You can inspect a
RouteData
object throughViewPage.ViewContext.RouteData
. Then check for values using something likeIf you find that you want to inspect these values in the controller instead, you can access them using ControllerBase.ControllerContext.RouteData. Something similar applies for action filters etc.
其他答案是正确的,但我想我会解决你的最后一句话:
部分视图是在视图本身中渲染的(除非从 JavaScript 调用并直接绑定到 DOM),使用以下代码:
因此,为了防止视图中出现“代码汤”(if 语句),您可以使用 HTML 帮助器来调用 RenderPartial检查 ViewContext 之后:
然后在视图中:
您可以对上面的内容进行一些修改 - 例如直接在扩展中访问路线数据,通过模型来绑定部分等 - 但您明白了。
或者,您可以在控制器中执行上述 IF 语句,并将部分视图名称填充到 ViewData 中,然后在视图中的常规 RenderPartial 调用中使用它。
任何能让你的船漂浮的东西。 :)
Other answers are correct, but thought i'd address your last sentence:
Well partial view's are rendered in the View itself (unless calling from JavaScript and binding directly to DOM) with the following code:
So to prevent "code soup" (if statements) in your view, you use a HTML helper which calls through to RenderPartial after inspecting the ViewContext:
And then in the View:
You could make some mods to the above - like access the route data directly in the extension, pass through the model to bind in the partial, etc - but you get the idea.
Alternatively you could do the above IF statement in your controller, and stuff the partial view name in the ViewData, then use that in the regular RenderPartial call in your View.
Whatever floats your boat. :)