0

I have a partialview in _Layout.cshtml that I only want to display for certain urls. My first thought was in my partial I would use a string as the model @model String . In the actionmethod that is called I would return this return PartialView("_MyPartial", new string{Request.FilePath}); In the partial I would have an if block wrapping my outer div that would check the model to see if the url it contained was the url that can display the partial.

I don't like this way because I would have to hardcode the url in if block check

@if( Model == "/Test/Home")
{
    <div>
       Just an example
    </div>

}

What would be the best way to do this?

Thanks

4

2 回答 2

3

您不需要使用硬编码字符串,即使您按照最初的预期在视图中进行了验证。

您可以使用

Request.Url.AbsolutePath

获取您当前的网址和

Url.Action("action", "controller")

生成不可接受的位置。

也就是说,我会让你的逻辑决定是否在你的控制器中显示部分视图。

if(showPartialView)
   return PartialView("_MyPartial");
else
   return new EmptyResult();
于 2012-05-03T23:27:39.300 回答
0

根据请求决定行动是控制器的责任。既然控制器选择了视图,为什么不让它也选择局部呢?找出你想要在你的控制器中的部分,如果有的话,并将它传递给你的视图模型上的视图。

于 2012-05-03T23:29:15.057 回答