使用Razor操纵动态javascript超链接

asp.net mvc - Manipute with Razor dynamic javascript hyperlinks

本文关键字:javascript 超链接 动态 操纵 Razor 使用      更新时间:2023-09-26

#refrigeratorDelete是一个超链接(a-标签),我可以有多个冰箱。根据冰箱的数量,我必须生成/操作超链接id并将其与唯一的冰箱id合并。但是变量i在[]里面是未知的。

我怎样才能解决这个问题?

 $(function () {
     for (var i = 0; i < @(Model.Refrigerators.Count()); i++) {
                $('#refrigeratorDelete@(Model.Refrigerators.ToList()[i]).on('click', function () {
                    // do stuff on single refrigerator
                });
            } 
});

更新
 @foreach (var refrigerator in Model.Refrigerators)
                    {
                        <li>    
                            <a id="refrigeratorDelete(@refrigerator.RefrigeratorId)" href="#">delete</a>
                        </li>
                    } 

更新2

 $('#refrigeratorDelete@(Model.RefrigeratorId)').on('click', function () {
            var title = 'title';
            var warningMessage = 'message';
            ShowYesNoWarningDialog(title, warningMessage, function () {
            // When OK/YES button is clicked call the server side action:
                document.location.href = '@(MVC.Devices.Refrigerator.Delete(Model.RefrigeratorId).Result.ToHRefUrl())';
            });
        });

说明:当有人点击删除链接时,一个带有Yes/No按钮的删除对话框打开。如果单击"否",则关闭对话框。如果单击是,也会关闭,但是ShowYesNoWarningDialog现在执行document.location.href =…发送到服务器的代码。在MVC内部…删除操作我无法传递客户端id,因为上下文未知。

Delete操作必须是非ajax调用,因为客户需要它!

在视图中为每个链接指定一个类名,并将Refrigerator的ID属性添加为data-属性

@foreach (var refrigerator in Model.Refrigerators)
{
  <li>    
    <a href="#" class="delete" data-id="@refrigerator.RefrigeratorId">delete</a>
  </li>
}

然后在脚本

var url = '@Url.Action("Delete", "controllerName")';
$('.delete').click(function() {
  var id = $(this).data('id'); // get the ID of the refrigerator
  var li = $(this).closest('li'); // in case you want to delete the li element
  $.post(url, { id: id }, function(response) {
    // if successful, use li.remove(); to remove the element
  });
});
上面的脚本假设您有一个类似于 的方法
[HttpPost]
public ActionResult Delete(int ID)
{
  // delete the refrigerator based on its ID
  return Json(true); // indicate success?
}

您需要为删除按钮添加一个类:

 @foreach (var refrigerator in Model.Refrigerators)
     {
         <li>
             <a id="refrigeratorDelete(@refrigerator.RefrigeratorId)" class="my-delete-btn" href="#">delete</a>
         </li>
     } 
当你像这样附加onclick事件时
$(function () {
    $('.my-delete-btn').on('click', function () {
        var currentId = this.id;
        // do stuff on single refrigerator
    });
});