MVC3 - Ajax.BeginForm和部分视图刷新

时间:2011-07-06 14:24:56

标签: c# asp.net-mvc-3 jquery

有没有办法刷新局部视图的一部分,还是应该将该部分分解为它自己独立的局部视图?我面临的问题是,每当我提交表单时,整个局部视图都会更新,复制我的表单输入,但我真的只想更新“noteList”。以下是一些可能有用的细节。

在我的项目中,我将一个页面拆分为单独的选项卡,每个选项卡都是自己的部分视图,当有人点击该选项卡时会加载该视图。我现在关注的那个是备注标签。

以下是捕获帖子的标记和控制器。

<div id="noteList">
    @Html.Grid(Model).Columns(column => {
        column.For(x => x.TimeStamp);
        column.For(x => x.UserName);
        column.For(x => x.Note);
        }).Attributes(Style => "text-aligh: center", @Class => "linkGrid")
</div>
<div id="addNoteForm">
    <h2>Add New Note</h2>
    @using (Ajax.BeginForm("AddNote", "Dispute", null, new AjaxOptions { UpdateTargetId = "noteList" }, new { id = "AddNote" })) {
        @Html.Hidden("DisputeID", ViewData["DisputeID"])
        <div class="editor-multiline-field">
            @Html.Editor("Note", "editor-multiline-field")
        </div>
        <input type="submit" value="Add Note" />        
    }
</div>

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddNote(FormCollection collection) {
    if (this.ModelState.IsValid) {
        DisputeNote newNote = new DisputeNote(repository.Get(int.Parse(collection["DisputeID"])), User.Identity.Name, collection["Note"]);
        repository.SaveForUpdate<DisputeNote>(newNote);
    }
    var Notes = repository.GetNotesForDispute(int.Parse(collection["DisputeID"]));
    ViewData["DisputeID"] = int.Parse(collection["DisputeID"]);
    return PartialView("NoteList", Notes);
}

我知道将其分解为另一个局部视图会起作用,但我很好奇是否有另一种方法可以做到这一点。

1 个答案:

答案 0 :(得分:2)

您需要使用其他部分视图按照此处列出的方式执行此操作 - 您无法使用相同的局部视图本身更新部分视图的一部分。但是:)还有其他选择 - 比如只返回JSON。 您可以使用.ajax()调用将JSON发布到控制器方法以添加注释。

查看这篇文章的粗略想法:

JSON / MVC (3P1) HttpPost - not getting it to work on my EF class