MVC Ajax jQuery复选框

时间:2014-08-19 20:16:54

标签: jquery ajax asp.net-mvc asp.net-mvc-4

------------更新代码---------------------

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

  <div class="person">
  <span>@Model.PeopleCheckBoxes.ToArray()[i].Username</span>

  @Html.CheckBoxFor(m => @Model.PeopleCheckBoxes.ToArray()[i].IsTaxExempt,
                    new { data_eventID = Model.catID, 
                          data_peopleID = Model.PeopleCheckBoxes.ToArray()[i].Id, 
                          @class = "PeopleCheckBox" }) 

   </div>

<script type="text/javascript">
    $(document).ready(function () {

        $('.PeopleCheckBox').change(function () {
            if (!$(this).is(':checked')) { // ignore checked items
                var url = '@Url.Action("RemoveMemberFromEvent2", "GiftList")';
                var eID = $(this).data('eventID');
                var pID = $(this).data('peopleID');

                $.post(url, { eventid: eID, peopleID: pid }, function (data) {
                    if (data) {
                        self.closest('.person').remove(); // remove the elements from the DOM
                    } else {
                        alert('Oops'); // the person was not removed
                    }
                });

            }
        });

  [HttpPost]
        public JsonResult RemoveMemberFromEvent2(int eventID, int peopleID) 
        {
             // database updated ..................
             return Json(true);
        }

------------结束更新代码---------------------

--------现在不使用这个局部视图;添加它只是为了看它是否可以使用-----

[HttpPost]
    public PartialViewResult RemoveMemberFromEvent(int eventID, int peopleID)
           {
              // removes checkbox from database :
              var aEvent = (from p in _EventMemberRepository.Table . . .
                _giftListService.DeletePersonOnGiftPage(aEvent);

                // queries database for new updated data : 
                var members2 = from c in _custRepository.Table  ....

                return PartialView("_RemoveMemberFromEvent", vModel);
            }

我想在取消选中复选框时运行一个方法, 并传递2个值。 做这件事的好方法是什么? 我想在jQuery中使用Ajax,但不知道如何编写代码:

@foreach (var item2 in Model.PeopleCheckBoxes)    
{
 @item2.Username 

 @Html.CheckBox("chkPeople", true, new {eventID = Model.catID, peopleID =item2.Id})
 ...

     public class GiftListController : Controller
        { 

     [HttpPost] 
            public ActionResult RemoveMemberFromEvent(int eventID, int peopleID) 
            {
                var aEvent = (from p in _EventMemberRepository.Table
                ............  
                return RedirectToAction("Index");
            }        

任何想法都赞赏。感谢

2 个答案:

答案 0 :(得分:2)

您正在创建无效的html,包括具有重复ID的复选框,您应该将这些值存储为自定义数据属性。而是使用foreach,使用for循环

@for (int i = 0; i < Model.PeopleCheckBoxes.Count; i++)
{
  <span>@Model.PeopleCheckBoxes[i].Username</span>
  @Html.CheckBoxFor(m => m.PeopleCheckBoxes[i].SomeProperty, true, new { data_eventID = Model.catID, data_peopleID = Model.PeopleCheckBoxes[i].ID, @class = "PeopleCheckBox")
}

或其IEnumerable

@{ var i = 0; }
@foreach (var item2 in Model.PeopleCheckBoxes)
{
  var id = "mycheckbox" + i;
  <span>@item2.Username</span>
  @Html.CheckBoxFor(m => item2.SomeProperty, true, new { data_eventID = Model.catID, data_peopleID = item2.ID, @class = "PeopleCheckBox", id = @id)
  i++;
}

请注意,添加了类名以用作jQuery选择器

脚本

$('.PeopleCheckBox').change(function () {
    if (!$(this).is(':checked')) { // ignore checked items
        var url = '@Url.Action("RemoveMemberFromEvent", "GiftList")';
        var eID = $(this).data('eventID');
        var pID = $(this).data('peopleID');
        $.post(url, { eventid: eID, peopleID: pid }, function (data) {
            // do something with the returned data if you want
        });
    }
});

但是你在action方法中进行重定向(它实际上不会在post方法的成功函数中返回任何内容)所以它不清楚为什么你采用这种方法而不是为每个{{创建一个表单元素1}}带有删除(提交)按钮。

修改

作为替代方法,您可以更改控制器操作方法以返回指示删除是否成功的JSON结果,如果是,则删除该项。这将允许用户留在页面上并继续删除没有重定向的其他项目。例如

person

并且在视图中,将与人员相关的所有控件包装在容器中,以便可以选择

[HttpPost]
public JsonResult RemoveMemberFromEvent(int eventID, int peopleID) 
{
  // delete member and return value indicating if successful
  if (isDeleted)
  {
    return Json(true);
  }
  else
  {
    return null;
  }
}

然后在脚本中

@for (int i = 0; i < Model.PeopleCheckBoxes.Count; i++)
{
  <div class="person">
    <span>@Model.PeopleCheckBoxes[i].Username</span>
    @Html.CheckBoxFor(m => m.PeopleCheckBoxes[i].SomeProperty, true, ...
  </div>
}

答案 1 :(得分:1)

您的视图看起来会像这样:

@Html.CheckBox("mycheckbox", new { onclick="customMethod()"})

有助于进行Ajax调用的JavaScript方法可以这样:

function customMethod(){
$.ajax({
        url: "@Url.Action("ActionMethod", "Controller")",
        type: "POST",
        async: true,
        dataType: "json",

        data: {
            variable1: '@Model.catID',
            variable2: '@item2.id'
        },

        success: function(data) {
            //If you have a response, it will be in the 'data' object
        }
    });
}

然后您的控制器将采用以下表格:

public string ActionMethod (int variable1, int variable2)
    {
        //Use your variables here and return your response, if any.
    }