2015-07-01 56 views
-1

我在寻找的东西非常简单,但它却在逃避我,我无法在任何地方找到一个好例子。ASP.NET MVC 5 jQuery AJAX主/细节表

我有实体的MVC剃刀循环:

@foreach (var item in Model) 
{ 
    <tr> 
     <td> 
      <a href="#" id="stockIndexLink"> 
       @Html.DisplayFor(modelItem => item.Name) 
      </a> 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Description) 
     </td> 
     <td> 
      @Html.ActionLink("Edit", "Edit", new { id = item.Id }) | 
      @Html.ActionLink("Details", "Details", new { id = item.Id }) | 
      @Html.ActionLink("Delete", "Delete", new { id = item.Id }) 
     </td> 
    </tr> 
    <tr id="componentRow"> 
     <td id="componentCell"> 
     </td> 
    </tr> 
} 

在jQuery中,我想详细PartialView加载到 'componentCell',有点像这样:

@section Scripts { 
    <script> 
     $(function() { 
      $("#componentRow").hide(); 

      $("#stockIndexLink").on("click", function() { 
       $("#componentRow").slideToggle(300, function() { 
        $("#componentCell").load('@Url.Action("GetStockIndices", "AdminStockIndex", new { id = 1 })'); 
       }); 
      }); 
     }); 
    </script> 
} 

。 ..你可以看到,我已经将id值硬编码到Url.Action中,只是为了看它。我如何从每一行中获取该ID,进入“点击”事件,而没有丑陋的黑客?此外,我知道我有一些工作要做,隐藏和切换的东西......但我可以处理。该id是什么让我绊倒。

谢谢!

+0

为什么downvote?无礼。 –

回答

3

你可以把网址中的锚href标记:

<a href="@Url.Action("GetStockIndices", "AdminStockIndex", new { id = item.Id })" class="stockIndexLink"> 
    @Html.DisplayFor(modelItem => item.Name) 
</a> 

和jQuery中:

$('.stockIndexLink').on('click', function(event) { 
    var $this = $(this), 
     url = $this.attr('href'); 

    var $componentRow = $this.closest('tr').next('.componentRow'); 
    var $componentCell = $componentRow.children('td').first(); 

    $componentRow.slideToggle(300, function() { 
     $componentCell.load(url); 
    }); 

    event.preventDefault(); 
}); 

编辑:另外请注意,在一些具有相同的其他答案的解释在多个元素上的id是违反html规范的,所以我改变了jQuery对象来搜索类。也更新,因此它不会选择所有组件行和单元格。 (从@Stephen Muecke的答案)

+0

当这个答案出现时,我通过使用'data-id'属性发布解决方案的一半,但这是一个更清洁的方法。好决定。 –

+1

仍然不正确 - 这将更新表中的每一行与'class =“componentRow”' –

+0

美丽,这是伎俩......谢谢! –

1

首先,你有,因为重复的id属性(id="stockIndexLink"id="componentCell"这意味着你只能永远做第一排东西反正你需要使用类名无效的HTML。最简单的方法是将Id属性存储为data-属性,在.click()事件

@foreach (var item in Model) 
{ 
    <tr> 
    <td> 
     <a href="#" class="stockIndexLink" data-id="@item.Id">@Html.DisplayFor(modelItem => item.Name)</a> 
    </td> 
    <td> 
     @Html.DisplayFor(modelItem => item.Description) 
    </td> 
    .... 
</tr> 
<tr class="componentRow"> 
    <td></td> 
</tr> 

}检索

那么你的脚本应该

$(".stockIndexLink").on("click", function() { 
    var id = $(this).data('id'); 
    var componentRow = $(this).closest('tr').next('.componentRow'); 
    var componentCell = componentRow.children('td').first(); 
    componentRow .slideToggle(300, function() { 
    componentCell .load('@Url.Action("GetStockIndices", "AdminStockIndex")', { id = id }); 
    }); 
}); 
+0

jQuery的新手,不知道类选择器能够做到这一点。感谢您的解释。一定会研究这个! –