如何在 Razor 中创建 else if 语句? [英] how to create an else if statement in Razor?

查看:45
本文介绍了如何在 Razor 中创建 else if 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在表格中显示一些行.根据用户组,视图应该显示不同的标记.管理员可以删除行,但版主只能将它们标记为可见或不可见.

I am trying to display some rows in a table. Depending on the UserGroup, the View should show different markup. An administrator can delete rows, but a moderator can only mark them as visible or invisible.

如何在 Razor 中编写正确的 if else 语句?

How do i write a proper if else statement in Razor?

页面显示正确,但页面标题解析错误

The page is displayed correctly, but the page title is Parse Error

这是我的代码:

@model MvcApplication3.Models.ViewModels.New.Question.MatrixRows

@{
    bool visible = Model.Visible;
}

<tr>
    <td>
    @if(visible) 
        {
        @Html.TextBoxFor(cn => Model.Row_Number, new { @class = "row required digits", size = 1 })
        }
    @if (!visible)
        {
        @Html.TextBoxFor(cn => Model.Row_Number, new { @class = "row required digits", size = 1, disabled = "disabled" })
        }
    </td>
    <td>
    @if(visible) 
        {
            @Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45 })
        }
    @if (!visible)
    {
        @Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45, disabled = "disabled" })
    }
    </td>
    <td>
        @if (HttpContext.Current.User.IsInRole("Administrator"))
        {
            @Html.HiddenFor(x => x.Delete, new { @class = "mark-for-delete" })
            @Html.LinkToRemoveNestedForm("Slet", "tr", "input.mark-for-delete")    
        }
        @if (HttpContext.Current.User.IsInRole("Moderator"))
        {
            @Html.HiddenFor(x => x.Visible, new { @class = "mark-for-visible" })
            @Html.LinkToDisableNestedForm("Deaktiver", "tr", "input.mark-for-visible")    
        }
        @Html.HiddenFor(id => Model.Row_Id)
    </td>
</tr>

推荐答案

由于您没有设置标题,标题有解析错误:

The title has parse error because you did not set a title:

@{
    ViewBag.Title = "Home Page";
}

现在对于 else 语句,不要使用回 @ 语法:

now for an else statement, don't use back the @ syntax:

@if(visible) 
{
    Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45 })
}
else
{
    Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45, disabled = "disabled" })
}

您正在检查一个布尔值,您只需要一个 else.同样对于 else if,它的工作原理是一样的.

You are checking for a boolean, you just need an else. Also for else if, it works the same.

只需执行以下操作即可进一步简化您的代码:

Your code could be simplified even more by just doing:

@Html.TextBoxFor(bs => Model.Row_Description, new { @class = "rowdesc", size = 45, disabled = visible ? "" : "disabled" })

因为无论如何您都在显示相同的代码,只需根据值更改属性即可.对我来说,这变得更具可读性.

Because you are displaying the same code anyways, just changing the attribute based on a value. To me, this becomes more readable.

这篇关于如何在 Razor 中创建 else if 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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