【问题标题】:IF ELSE html helper in razor view?IF ELSE html helper 在剃刀视图中?
【发布时间】:2015-06-02 00:42:07
【问题描述】:

我想在 Razor 视图中使用 IF ELSE 语句。是否可以使用 IF( html.helper ) 然后做点什么?或者有什么建议?

@using (Html.BeginForm())
{
    <table>

            @for (int i = 0; i < Model.Count; i++)
            {
                <tr>
                    <td>
                        @Html.HiddenFor(m => m[i].Question_ID)
                        @Html.HiddenFor(m => m[i].Type)
                        @Html.DisplayFor(m => m[i].Question)
                    </td>
                </tr>
                <tr>
                    @if(@Html.DisplayFor(m=> m[i].Type =="Info_Text") **
                    {
                        <td>
                              //DO NOTHING
                        </td>                
                    }
                    else
                    { 
                    <td>
                        @Html.EditorFor(m => m[i].Answer)
                    </td>
                    }
                </tr>
            }

    </table>

【问题讨论】:

  • 你也试过了吗?它是否给出了一些错误..发布它
  • 为什么必须在 html.helper 上使用 if 语句,而不是在模型中的项目上使用?
  • 有什么特别的原因为什么您不只测试m[i].Type == "Info_Text" 而不是DisplayFor
  • 大家好,我对 Razor 还是很陌生,还在摸索中。 @DaveWard 感谢您的回答有效!我虽然它必须与 html.helper 一起使用。
  • @Edward.K:别担心,我们都还在摸索中。我添加了一些额外信息的答案,这些信息可能有助于澄清与此相关的一些问题。

标签: asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

正如我在评论中提到的,您可以直接测试m[i].Type 的值:

@if (m[i].Type == "Info_Text") {
  <td></td>
} else {
  <td>@Html.EditorFor(m => m[i].Answer)</td>
}

您不会针对DisplayFor 的值进行测试的原因是它返回MvcHtmlString,而不仅仅是像stringint 这样的简单类型。如果有一天你发现需要与DisplayFor 进行比较,你可以做这样的事情(希望这会让这一切变得更有意义):

@if (Html.DisplayFor(m => m[i].Type) == new MvcHtmlString("Info_Text"))

由于您正在学习 MVC,您可能还对如何自定义 EditorFor 帮助程序以自动执行此操作感兴趣:http://www.hanselman.com/blog/ASPNETMVCDisplayTemplateAndEditorTemplatesForEntityFrameworkDbGeographySpatialTypes.aspx

【讨论】:

    【解决方案2】:

    为什么必须使用 DisplayFor?你有什么特别的原因吗?

    如果你用呢

    if(Model[i].Type =="Info_Text")
    {
    <td>
        //DO NOTHING
    </td>
    }
    

    【讨论】:

    • 这是@DaveWard 在评论中所说的。你做了什么不同的事情?
    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    相关资源
    最近更新 更多