想从for循环中获取@ Html.HiddenFor的不同值

时间:2013-09-21 07:34:21

标签: c# javascript jquery asp.net-mvc-4 razor

每次用户点击图片时,如何在我的javascript中获取完全“PostId”的值

for (int i = 0; i < Model.Count; i++)
{

<img src="/images/icon_edit.gif" width="22" height="19" class="Edit" itemid="post" />
@Html.HiddenFor(x => x[i].PostId, new { @class = "postnew" })    
}

JS:

$(document).ready(function () {
  $('.Edit').click(function () {
      alert($("#post").val());

      var params = { uname: $(this).val() };

      $.ajax({
          url: "/Profile/Post",
          type: "Get",
          data: { id: $("#post").val() }     
      });
  });
});

2 个答案:

答案 0 :(得分:2)

您可以将帖子ID呈现为data attribute并使用jQuery访问它。

@for (int i = 0; i < Model.Count; i++)
{    
  <img src="/images/icon_edit.gif" width="22" height="19" class="Edit" data-post-id="@x[i].PostId" />   
}

jQuery的:

$(document).ready(function () {
  $('.Edit').click(function () {
      var $this = $(this), id = $this.data('postId');

      $.ajax({
          url: "/Profile/Post",
          type: "Get",
          data: { id: id }     
      });
  });
});

生成的img标记看起来像:

 <img src... data-post-id="1" ... />

使用jQuery,您可以使用.data()读取属性。由连字符分隔的名称将是camelCased,因此postId

但是,我们可以做得更好......

  1. 考虑使用.on处理用.Edit修饰的元素的所有当前和未来点击事件。如果以后可能会将带有.Edit的新元素添加到DOM中,这将非常有用,因为它们将自动包含在内。

     $(document).on('click', '.Edit', function() { /* ... */ });
    
  2. 考虑使用语义上有意义的标记,并将图像包装在锚点中,而不是使img可点击。然后,只需将锚点href添加到帖子的URL即可。然后,您可以取消数据属性,只需取消AJAX调用。

    @for (int i = 0; i < Model.Count; i++)
    {    
       <a href="@Url.Action("Post", "Profile", new{id = x[i].PostId})" class="Edit"><img src="/images/icon_edit.gif" width="22" height="19" /></a>
    }
    
    $(document).ready(function () {
      $(document).on('click', '.Edit', function () {
          var url = $(this).attr('href');
    
          $.ajax({
              url: url,
              type: "Get"  
          });
      });
    });
    

答案 1 :(得分:0)

具有数据属性的解决方案很好但如果您想使用隐藏字段,则可以使用jQuery next()选择器。

$(document).ready(function () {
  $('.Edit').click(function () {

      // the 'next' hidden field for the img
      var id = $(this).next().val(); 

      $.ajax({
          url: "/Profile/Post",
          type: "GET",
          data: { id: id }     
      });
  });
});