中止/跳过/取消剃刀视图的渲染 [英] Abort/skip/cancel the rendering of a Razor view

查看:73
本文介绍了中止/跳过/取消剃刀视图的渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

许多开发人员都这样做:

Many devs do this:

public void foo() {
  if (flag) {
    // do stuff
  }
}

我宁愿早点回来",也可以这样做:

I prefer to "return early", and so do this instead:

public void foo() {

  if (!flag) return;

  // do stuff

}

在ASP.NET-MVC剃刀视图中,中止/跳过/取消视图/部分视图的呈现的正确方法是什么?例如,我如何转换它:

In an ASP.NET-MVC Razor view, what is the correct way to abort/skip/cancel rendering of a view/partialview? For example how do I convert this:

@if (flag) {
  // do stuff
}

类似这样:

@if (!flag) { /* what do I do here to abort/skip/cancel the rendering? */ }

// do stuff

我尝试使用return并使用Request,但是不确定这会如何影响该过程.正确的方法是什么?

I've tried using return and playing with the Request, but am unsure how this affects the process. What is the correct way to do this?

推荐答案

如上所述,您只需发出return.

As I mentioned above, you can simply issue a return.

我记得cshtml文件是在运行时编译的,其中包括所有内联代码以及静态html.这意味着从理论上讲,我希望所有代码都保持原样,并且不会以任何方式进行转换.

I recall cshtml files are compiled at runtime, which includes all inline code as well as the static html. That means that in theory, I'd expect any code to be left as-is and not transformed in any way.

因此,如果您这样做:

@if (!flag) { return; }

// do stuff

正常工作(至少对我来说).我只是想知道这是否会导致任何意想不到的副作用.

It works as expected (well for me at least). I just wanted to know if this leads to any unintended side-effects.

这篇关于中止/跳过/取消剃刀视图的渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆