3

myClient我的 Razor 代码中的变量范围存在问题。我确信解决方案很简单。基本上我在一个单独的@{}块中引用它,这可能会导致问题,但似乎除非我这样做,否则我会if..{}在 HTML 中获得代码。

@{
int i = 0;
foreach (var item in Model.Clients)
    {
        Int32 myId = Convert.ToInt32(item.DBID);
        var myClient = db.Client.Where(c => c.Id == myId).First();
    <td>
        <table class="inner">
        <tr><th>
            @string.Format(
                "{0} {1} {2}",
                myClient.Title,
                myClient.Initials,
                myClient.LastName)

                @{
                    if (myClient.Type!="Primary")
                    {
                        @Html.ActionLink(
                            "Delete", 
                            "Delete", 
                            "ClientBackground", 
                            new { id=item.ID }, null)
                    }
                 }
            </th></tr>
        }
        <table>

我的代码无法引用myClient.Type。如果我删除周围@{},那么我会在 HTML 中获得 c# 代码。

我知道一些简单的事情,但我没有看到它。

非常感谢任何帮助。

编辑:表关闭。

4

2 回答 2

2

试试这个:

<table class="inner">
              @{int i = 0;}

              @foreach (var item in Model.Clients)
                  {
                      Int32 myId = Convert.ToInt32(item.DBID);
                      var myClient = db.Client.Where(c => c.Id == myId).First();


                            <tr><td>@string.Format("{0} {1} {2}",myClient.Title,myClient.Initials,myClient.LastName)
                                    @if (myClient.Type!="Primary")
                                        {
                                        @Html.ActionLink("Delete", "Delete","ClientBackground", new { id=item.ID },null)
                                }

                    </td></tr>
              }

</table>

我对格式做了很多猜测。重要的是,我将您的 int 分配放入它自己的块中。我把开头和结尾<tr>的和<td>'s 匹配,并将它们放在可选之外@if blocks。但是这个版本会编译。

于 2013-04-11T12:58:17.793 回答
1

这里有奇怪的语法:

@{if (myClient.Type!="Primary")
     {
          @Html.ActionLink("Delete", "Delete","ClientBackground", new { id=item.ID },null)
     }
 }

为什么不:

@if (myClient.Type!="Primary")
{
   @Html.ActionLink("Delete", "Delete","ClientBackground", new { id=item.ID },null)
}

添加:

您更新的代码包含无效的 html 标记,它应该类似于:

<table class="inner">
@{
int i = 0;
foreach (var item in Model.Clients)
{
    Int32 myId = Convert.ToInt32(item.DBID);
    var myClient = db.Client.Where(c => c.Id == myId).First();
    <tr><th>
        @string.Format("{0} {1} {2}", myClient.Title, myClient.Initials, myClient.LastName)
        @if (myClient.Type!="Primary")
        {
            @Html.ActionLink("Delete", "Delete", "ClientBackground", new { id=item.ID }, null)
        }
    </th></tr>
}
</table>

表未关闭,您已打开<td>标签

于 2013-04-11T12:59:49.830 回答