我有一个DIV(tenant-reference-photos
),其中包含显示照片的局部视图。每张照片旁边都有一个删除按钮。单击它时,我希望从列表中删除照片,并且只需要由Ajax更新DIV。
我正在使用Ajax.ActionLink
进行删除操作:
<div>
@Ajax.ActionLink("Delete", "DeleteReference",
new { id = photo.ImageId },
new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST",
UpdateTargetId = "tenant-reference-photos" },
new { @class = "btn btn-primary" })
</div>
控制器操作:
[HttpGet]
public ActionResult DeleteReference(int id)
{
return View(refPhotoRepository.Find(id));
}
[HttpPost, ActionName("DeleteReference")]
public ActionResult DeleteReferenceConfirmed(int id)
{
try
{
refPhotoRepository.Delete(id);
refPhotoRepository.Save();
return PartialView("_TenantReferencePhotosPartial");
}
catch (Exception e)
{
// handle exception
}
return View();
}
当我单击“删除”时,将触发操作并从数据库中删除记录。问题出在return PartialView("_TenantReferencePhotosPartial");
上。当操作尝试返回partial时,我在@if (Model.ReferencePhotos.Count == 0)
得到NullReferenceException。
_TenantReferencePhotosPartials.cshtml
<div>
@if (Model.ReferencePhotos.Count == 0)
{
<h3>You haven't uploaded any references!
@Ajax.ActionLink("Upload now?",
"TenantUploadReference",
new AjaxOptions
{
UpdateTargetId = "tenant-reference-photos",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
LoadingElementId = "ajax-loader"
})</h3>
}
else
{
foreach (var photo in Model.ReferencePhotos)
{
<ul class="thumbnails">
<li class="span8">
<a href="#" class="thumbnail">
<img src="@Url.Action("GetReference", "Tenants", new { id = photo.ImageId })" alt="@photo.Name") />
</a>
</li>
<li class="span4 btn-group btn-group-vertical">
<a href="#" class="btn btn-primary" id="showEditPhotoModal" role="button" data-toggle="modal">Edit</a>
@Ajax.ActionLink("Delete", "DeleteReference",
new { id = photo.ImageId },
new AjaxOptions { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", UpdateTargetId = "tenant-reference-photos" },
new { @class = "btn btn-primary" })
</li>
</ul>
}
}
</div>
即使集合中有多张照片并且其中一张已被删除,但前面提到的行仍然会抛出异常。一些帮助将不胜感激。
答案 0 :(得分:2)
如何解决上述错误?
我遇到了一些问题,即jQuery $甚至没有在partials中定义 虽然它在源头
我相信这与你的问题有关。当我在局部视图中遇到这个时,对我来说总是有用的是将它包含在script section
中。因此,在您编写脚本的_Layout.cshtml
上,您可以添加以下内容:
// Do this after you referenced jquery
@RenderSection("scripts", required: false)
<script>
// some script references
</script>
然后在您的视图中执行此操作:
@section scripts {
$(function() {
<script>
function onDeleteReferenceSuccess(data, status, xhr) {
if (data.error) { /* handle error */ }
else {
window.location.reload(true);
}
}
</script>
});
}
一旦解决了上述问题,我该如何更新唯一的DIV? 由于您删除了该项目,我认为您将要删除div - 表示该项目。
如果我的假设是正确的,那么为什么不给它Id
,这样你就可以在else
声明中将其删除:
else {
// instead of this -> window.location.reload(true);
$("#id_of_the_div").remove();
}
<强>更新强> 您更新的问题抛弃了我原来的答案。但是,我先在这里包括更新后的答案(然后再进行清理)。因此,您有一个空引用错误的原因是因为您没有返回模型:
refPhotoRepository.Delete(id);
refPhotoRepository.Save();
// build the model here and pass it to the partial view
// this will most probably involve querying your data store again
var model = goBuildTheModel();
return PartialView("_TenantReferencePhotosPartial", model;