簡體   English   中英

來自復選框的Mvc Ajax部分視圖

[英]Mvc Ajax post from check-boxes in partial view

我有一個局部視圖,用於在剃刀中的表格列中顯示一個復選框。 當我單擊表中的任何復選框時,其回發到控制器的第一行ID而不是包含復選框的行ID。 發出ajax請求的javascript函數為“ SaveChanges”,如下所示。 隱藏的字段“ RecurrenceScheduleId”是主鍵ID。

我在這里做錯什么了嗎?

-以下是我的視圖和控制器操作:

  @model SMRDS.Model.RecurrenceSchedule

  @using (Ajax.BeginForm("_LogOccurancePartial", "Schedule",
            new AjaxOptions
            {
                UpdateTargetId = "tdOccurance",
                HttpMethod = "post",
                LoadingElementId = "btnProgress",
                OnBegin = "dialogBegin",
                OnSuccess = "updateSuccess",
                OnFailure = "dialogFailure"
            },
            new { id = "frm-toggle" }))
           {

            @Html.HiddenFor(model => model.RecurrenceScheduleId)
            @Html.CheckBoxFor(m => m.LogOccurences, new { @onclick ="SaveChanges(this)" })
            }
<script> 

function updateSuccess() {}

function dialogFailure() {}

function dialogComplete() {}

function dialogBegin() {}

function SaveChanges(checkboxInput) {
    $.ajax({
        type: 'POST',
        url: '/Schedule/_LogOccurancePartial',
        data: { newValue: checkboxInput.checked, id: $("#RecurrenceScheduleId").val() },
        dataType: 'json',
        success: function (response) {
           //handle success
        }
    });
}

控制器動作:

 public JsonResult _LogOccurancePartial(bool newValue,int id)
 { 
        var result = BLL.Service.RecurrenceSchedules.UpdateLogOccurence(id, newValue);

        return Json(new { result = result }, JsonRequestBehavior.AllowGet);
 }

更新資料

以下是為隱藏字段呈現的html。 目前,我只有兩行,其ID為“ 40”和“ 41”。

<input data-val="true" id="RecurrenceScheduleId"
    name="RecurrenceScheduleId" type="hidden" value="40"> 

<input data-val="true" id="RecurrenceScheduleId"
    name="RecurrenceScheduleId" type="hidden" value="41">

使用助手時,您有責任維護唯一的ID。

如果你有模特

public class ViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

並且您的視圖包含一個集合,您可以使用帶索引的for循環使用唯一值覆蓋id。

@model List<ViewModel>

@for(int i = 0; i < Model.Count(); i++)
{
    @Html.HiddenFor(m => Model[i].Id, htmlAttributes: new { id = "item" + item.Id })    
}

但是,您也可以調整點擊處理程序,因此您無需按ID查找隱藏的輸入。

@Html.CheckBoxFor(m => m.LogOccurences,
    new { @class="trigger", data_rsid=m.RecurrenceScheduleId })

<script>
    $("body").on("click", ".trigger", function(e) {
        var rsId = $(this).data("rsid");
        var checked = $(this).prop("checked");
        var data = { newValue: checked, id: rsId }
        $.ajax({ ... });
    });
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM