使用MVC Ajax在部分视图中更新部分视图
我有一个MVC 5 Web应用程序,它包含一个名为CreateProposal的Razor View,它接受一个名为ProposalViewModel的ViewModel。 此视图包含对名为_Proposal的部分视图的引用,该部分视图也接受ViewModel。
CreateProposal视图
@model STAR.UI.ViewModels.ProposalViewModel @Html.Partial("_Proposal", Model)
部分视图_Proposal还引用了另一个名为_ExistingAttachments的部分视图,它也接受ViewModel。
_Proposal Partial
@model STAR.UI.ViewModels.ProposalViewModel @Html.Partial("_ExistingAttachments", Model)
_ExistingAttachments Partial
@model STAR.UI.ViewModels.ProposalViewModel
@Html.Hidden("hiddenAttachmentID", "", new { @id = "hiddenAttachmentID" }) @if (Model.Attachments != null) { foreach (var upload in Model.Attachments) { @upload.fileName Remove
} }
_ExistingAttachments Partial吐出一个href链接列表和每个旁边的Remove链接。 一旦用户单击要删除的项目上的删除链接,该条目的ID就会使用一些JQuery存储在隐藏文本框中。
JQuery的
$(document).on('click', '.btn.btn-danger', function () { var id = $(this).data('id'); //alert(id); $('#hiddenAttachmentID').val(id); });
然后向用户呈现模态确认框,一旦确认删除,就会进行Ajax调用,然后更新部分_Proposal中的Partial _ExistingAttachments
$.ajax({ type: "GET", url: '/Proposal/DeleteAttachment/', data: { id: $("#hiddenAttachmentID").val() }, error: function () { alert("An error occurred."); }, success: function (data) { alert("Worked."); $("#proposalAttachments").html(data); } });
MVC控制器
public ActionResult DeleteAttachment(int id) { //Delete entry using passed in id ProposalViewModel model = new ProposalViewModel(); //Code to populate ViewModel return PartialView("_ExistingAttachments", model); }
一切正常,直到我期望刷新Partial View _ExistingAttachments ,但这不会发生。
为长期问题道歉,但希望能发现我做错了什么。
请帮忙。
UPDATE
我应该补充一下,代码使它成为Ajax Success函数和alert(“Worked。”); 叫做。 但是,不是部分刷新,而是调用同一个Controller中的编辑操作
[HttpPost] public ActionResult EditProposal(ProposalViewModel model)
在Jasen的帮助下,人们终于得到了解决。 在我的Ajax调用完成后,代码然后重定向到另一个页面。 显然我不希望这种情况发生,因为我只是希望部分视图在我的页面上更新,但随后保留在页面上。
罪魁祸首实际上是我的模态中的确认按钮。 它是
这导致应用程序在Ajax调用后执行POST。 所以我改为这个
现在一切都按预期工作了。
似乎所有标记和代码块都很好。 可能你的ajax get请求被缓存了
尝试将cache:false
添加到您的ajax调用中
$.ajax({ type: "GET", url: '/Proposal/DeleteAttachment/', cache: false, data: { id: $("#hiddenAttachmentID").val() }, error: function () { alert("An error occurred."); }, success: function (data) { console.log("Worked."); $("#proposalAttachments").html(data); } });