【问题标题】:MVC C# view is not allowing if statement in tagMVC C# 视图不允许标记中的 if 语句
【发布时间】:2012-04-16 20:56:25
【问题描述】:

我有一些类似的代码:

<table class="invisibleforprint">
    <thead>
        <tr class="mainheader">
            <th>@Html.ActionLink("Invoice Number", "Index", new { sortOrder= ViewBag.NumberSortParm })</th>
        </tr>
    </thead>
    <tbody>
    @foreach (var item in Model) {
        <tr>
            <td class="invoiceActions">
                <input type="button" class="btnresetinvoice button" value="Reset" data-invoiceid="@item.InvoiceId" />
            </td>
        </tr>
    }</tbody>
</table>

编译得很好。我去并在输入中添加了一个 if 语句:

<table class="invisibleforprint">
    <thead>
        <tr class="mainheader">
            <th>@Html.ActionLink("Invoice Number", "Index", new { sortOrder= ViewBag.NumberSortParm })</th>
        </tr>
    </thead>
    <tbody>
    @foreach (var item in Model) {
        <tr>
            <td class="invoiceActions">
                <input type="button" class="btnresetinvoice button" value="Reset" data-invoiceid="@item.InvoiceId" @{ if(item.PMApproved != true) { @:disabled="disabled" } } />
            </td>
        </tr>
    }</tbody>
</table>

它给出了错误'}预期'

说什么?我添加了等量的左括号。

谁知道我做错了什么?

【问题讨论】:

  • 为什么不使用助手?这看起来像一个糟糕的标签汤。

标签: c# html asp.net-mvc razor


【解决方案1】:
<input type="button" class="btnresetinvoice button" value="Reset" data-invoiceid="@item.InvoiceId" @(item.PMApproved != true ? "disabled='disabled'" : "" ) />

【讨论】:

    【解决方案2】:
    <input type="button" value="Reset" data-invoiceid="@item.InvoiceId" @(item.PMApproved ? "disabled=\"disabled\"" : null) />
    

    或者你可以使用@if&lt;text&gt;标签:

    <input type="button" value="Reset" data-invoiceid="@item.InvoiceId" @if(item.PMApproved) { <text>disabled="disabled"</text>} />
    

    【讨论】:

      【解决方案3】:

      不要在 if 语句周围使用花括号,而应该使用普通括号。

      即:

      @( if(item.PMApproved != true) { @:disabled="disabled" } )
      

      你可以试一试吗?

      【讨论】:

      • 试过了,好像不喜欢
      • 顺便说一句,没有必要将布尔值与真/假进行比较。你可以简单地写if(item.PMApproved) { ... }
      • 在这种情况下我这样做是因为它是一个可为空的布尔值
      【解决方案4】:

      您可以执行以下色情内容(但请不要):

      <input type="button" class="btnresetinvoice button" value="Reset" data-invoiceid="@item.InvoiceId" @Html.Raw(item.PMApproved ? "disabled=\"disabled\"" : "") />
      

      或者像我一样使用助手suggested you:

      @Html.ApproveButton(item)
      

      【讨论】:

        猜你喜欢
        • 2014-02-13
        • 1970-01-01
        • 2013-06-11
        • 1970-01-01
        • 2011-06-02
        • 1970-01-01
        • 2015-11-01
        • 1970-01-01
        • 2014-05-29
        相关资源
        最近更新 更多