可编辑表行的MVC Ajax表单

时间:2015-12-05 17:19:55

标签: c# ajax asp.net-mvc

我有以下部分视图

@model Marks.Web.ViewModels.AssignmentMarkViewModel

<div class="table">
    @using (Ajax.BeginForm("_MarkInlineEditor", "Semesters", new AjaxOptions
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "editor" + Model.AssignmentId
    }, new { @id = "editor" + Model.AssignmentId, @class = "tr" }))
    {
        <span class="td">@Model.AssignmentName</span>
        <span class="td">@(Model.Mark.HasValue ? Model.Mark.Value.ToString("#.##") : "")</span>
        <span class="td">@Model.Weight.ToString("#.##")</span>
        <span class="td">@(Model.ActualMark.HasValue ? Model.ActualMark.Value.ToString("#.##") : "")</span>
        @Html.HiddenFor(model => model.AssignmentId)
        <span class="td"><button type="submit" name="option" value="edit">Edit</button></span>
        <span class="td"><button type="submit" name="option" value="clear">Clear</button></span>
    }
</div>

单击“编辑”按钮时,操作方法将返回另一个局部视图,该视图用作编辑视图:

@model Marks.Web.ViewModels.AssignmentMarkViewModel

<div class="table">
    @using (Ajax.BeginForm("_MarkInlineViewer", "Semesters", new AjaxOptions
    {
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        UpdateTargetId = "viewer" + Model.AssignmentId
    }, new { @id = "viewer" + Model.AssignmentId, @class = "tr" }))
    {
        <span class="td">@Html.TextBoxFor(m => m.AssignmentName)</span>
        <span class="td">@Html.TextBoxFor(m => m.Mark)</span>
        <span class="td">@Html.TextBoxFor(m => m.Weight, new { required="required", type="number" })</span>
        <span class="td">xx</span>
        @Html.HiddenFor(model => model.AssignmentId)
        <span class="td"><button type="submit" name="option" value="save">Save</button></span>
        <span class="td"><button type="submit" name="option" value="cancel">Cancel</button></span>
    }
</div>

当我点击“保存”按钮时,调用的操作方法应为_MarkInlineViewer,而是调用_MarkInlineEditor。我是怎么做的?以下是行动方法:

public PartialViewResult _MarkInlineEditor(string option, int assignmentId)
{
    var marksRepo = new MarksRepo();
    var mark = marksRepo.GetMarkById(assignmentId);
    var markVm = Mapper.Map<AssignmentMarkViewModel>(mark);
    return PartialView(option == "edit" ? "_MarkInlineEditor" : "_MarkInlineViewer", markVm);
}

public PartialViewResult _MarkInlineViewer(AssignmentMarkViewModel amvm)
{
    var marksRepo = new MarksRepo();
    var mark = Mapper.Map<AssignmentMark>(amvm);
    var updatedMark = marksRepo.UpdateMark(mark);
    var updatedAmvm = Mapper.Map<AssignmentMarkViewModel>(updatedMark);

    return PartialView("_MarkInlineViewer", updatedAmvm);
}

1 个答案:

答案 0 :(得分:0)

事实证明,我无法取代我正在尝试的工作形式,所以对于我的UpdateTargetId我使用了父div而不是形式&#39; s ID。