干净的方式返回一个空的mvc局部视图

Ins*_*dBy 17 c# asp.net-mvc asp.net-mvc-partialview

在cshtml文件中,根据条件,返回空部分视图的最佳方法是什么?

现在我有:

@if(Model.Count() > 0)
{
  loooonng partial view block of markup code
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能重新做到更接近这个看起来更干净:

@if(Model.Count() == 0)
{
  render an empty partial view
}

  loooonng partial view block of markup code goes here   <- This will obviously get executed only if Model.Count() > 0
Run Code Online (Sandbox Code Playgroud)

提前致谢 !

Ema*_*uel 15

不确定你是否还需要答案,但我遇到了这个问题,这就是我在视图中所做的:

@if(Model.Count() == 0)
{
return; // a simple return will stop execution of the rest of the View
}
Run Code Online (Sandbox Code Playgroud)

在Controller级别,我创建了一个新类并在我的操作中返回它:

public class EmptyPartialViewResult : PartialViewResult
{
    public override void ExecuteResult(ControllerContext context)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)


Asi*_*taq 14

我一直在用

return Content("");
Run Code Online (Sandbox Code Playgroud)

并且工作正常.

  • 无法将ContentResult转换为PartialViewResult:/ (12认同)

Chr*_*ris 12

如果您要返回,PartialViewResult我发现在控制器中您可以使用

return default(PartialViewResult);
Run Code Online (Sandbox Code Playgroud)

要么

return null;
Run Code Online (Sandbox Code Playgroud)

没有任何问题.我能想到的唯一考虑因素是你是否正在使用

var partialView = Html.Action("Action", "Controller");
Run Code Online (Sandbox Code Playgroud)

在您的视图中,您将需要检查null.Html.RenderAction似乎接受它没问题.


Bac*_*cks 5

使用EmptyResult类:

return new EmptyResult();
Run Code Online (Sandbox Code Playgroud)

  • 如果控制器方法返回类型是 PartialViewResult,这将不会编译 (6认同)