在Razor CSHTML中切换语句

Leo*_*lva 16 c# asp.net asp.net-mvc razor asp.net-mvc-4

我正在ASP.NET MVC4,Twitter.Bootstap 3.0.0和Razor中开发一个项目.在视图中,我需要根据属性值显示按钮.使用该switch语句,下面的示例不起作用(不显示任何内容):

@switch (Model.CurrentStage) { 
    case Enums.Stage.ReadyToStart:
        Html.ActionLink(Language.Start, "Start", new { id=Model.ProcessId }, new { @class = "btn btn-success" });
        break;
    case Enums.Stage.Flour:
        Html.ActionLink(Language.GoToFlour, "Details", "Flours", new { id=Model.Flour.FlourId }, new { @class = "btn btn-success" });
        break;
    ...
}
Run Code Online (Sandbox Code Playgroud)

使用<span>标记更改位,代码可以正常工作:

@switch (Model.CurrentStage) { 
    case Enums.Stage.ReadyToStart:
        <span>@Html.ActionLink(Language.Start, "Start", new { id=Model.ProcessId }, new { @class = "btn btn-success" })</span>
        break;
    case Enums.Stage.Flour:
        <span>@Html.ActionLink(Language.GoToFlour, "Details", "Flours", new { id=Model.Flour.FlourId }, new { @class = "btn btn-success" })</span>
        break;
    ...
}
Run Code Online (Sandbox Code Playgroud)

有人可以解释原因吗?

谢谢.

Joe*_*nos 22

这是Razor的乐趣.当您使用普通HTML并使用C#代码时,@在其上放置带符号的内容会将结果写入页面:

<p>@Html.ActionLink("whatever", "whatever"...)</p>
Run Code Online (Sandbox Code Playgroud)

这与老派相似<%= %>.

<p><%= SomeMethodThatReturnsSomethingThatWillBeWritten() %></p>
Run Code Online (Sandbox Code Playgroud)

但是,Html.ActionLink方法只返回MvcHtmlString.NET世界中的对象.在您的第一个示例中,您有一个常规的C#代码块.所以Html.ActionLink()从那里调用只是执行它并返回MvcHtmlString到nobody.在第二个示例中,您已经跳回到HTML上下文中,因此它再次编写HTML.

You can use the special <text> block to get back to HTML instead of using <span> or other real HTML, and it will write directly without writing the extra HTML:

case Enums.Stage.ReadyToStart:
    <text>@Html.ActionLink(Language.Start, "Start", new { id=Model.ProcessId }, new { @class = "btn btn-success" })</text>
    break;
Run Code Online (Sandbox Code Playgroud)

You can also use the similar @: syntax:

case Enums.Stage.ReadyToStart:
    @:@Html.ActionLink(Language.Start, "Start", new { id=Model.ProcessId }, new { @class = "btn btn-success" })
    break;
Run Code Online (Sandbox Code Playgroud)

You can read more about both here

EDIT

Actually, in this case, you don't need either one. You just need the @ symbol, which will be enough to get you back into the HTML:

case Enums.Stage.ReadyToStart:
    @Html.ActionLink(Language.Start, "Start", new { id=Model.ProcessId }, new { @class = "btn btn-success" })
    break;
Run Code Online (Sandbox Code Playgroud)