简体   繁体   English

MVC4 - 删除对象后刷新部分视图,Ajax.ActionLink意外动作

[英]MVC4 - refreshing partial view after deleting object with Ajax.ActionLink acting unexpectedly

I have a DIV ( tenant-reference-photos ) that holds a partial view that display photos. 我有一个DIV( tenant-reference-photos ),其中包含显示照片的局部视图。 Beside each photo is a delete button. 每张照片旁边都有一个删除按钮。 When it's clicked, I want the photo to be removed from the list and only the DIV to be updated by Ajax. 当它被点击时,我希望从列表中删除照片,并且只需要由Ajax更新DIV。

I'm using an Ajax.ActionLink for the delete action: 我正在使用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>

Controller actions: 控制器动作:

[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();
}

When I click delete, the action fires and record is deleted from the database. 单击“删除”时,将触发操作并从数据库中删除记录。 The problem is with return PartialView("_TenantReferencePhotosPartial"); 问题是return PartialView("_TenantReferencePhotosPartial"); . When the action tries to return the partial, I get a NullReferenceException at @if (Model.ReferencePhotos.Count == 0) . 当动作尝试返回partial时,我在@if (Model.ReferencePhotos.Count == 0)处得到NullReferenceException。

_TenantReferencePhotosPartials.cshtml _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>

Even if there are several photos in the collection and one is deleted, the exception is still thrown at the line mentioned previously. 即使集合中有多张照片并且其中一张被删除,但仍然会在前面提到的行中抛出异常。 Some help would be appreciated. 一些帮助将不胜感激。

How do I resolve the above error? 如何解决上述错误?

I've had some trouble with jQuery $ not being defined in partials even though it's there in the source 我有一些麻烦,jQuery $没有在partial中定义,即使它在源代码中存在

I believe this is in connection with your problem. 我相信这与你的问题有关。 When I encounter this on a partial view, what always works for me is to include it in a script section . 当我在局部视图中遇到这个时,对我来说总是有用的是将它包含在script section So on your _Layout.cshtml where you write your scripts you can add this: 所以在您编写脚本的_Layout.cshtml ,您可以添加以下内容:

// Do this after you referenced jquery
@RenderSection("scripts", required: false)
<script>
// some script references
</script>

Then on your view you do this: 然后在您的视图中执行此操作:

@section scripts {
    $(function() {
        <script>
            function onDeleteReferenceSuccess(data, status, xhr) {
                if (data.error) { /* handle error */ }
                else {
                    window.location.reload(true);
                }
            }
        </script>
    });
}

Once above is resolved, how do I update the only the DIV? 解决上述问题后,如何更新DIV? Since you deleted the item I would assume you would want to delete the div - that represents the item. 由于您删除了该项目,我认为您将要删除div - 表示该项目。

If my assumption is correct then why not give it an Id so you can delete it afterwards in your else statement: 如果我的假设是正确的,那么为什么不给它一个Id所以你可以在你的else语句中删除它:

else {
    // instead of this -> window.location.reload(true);
    $("#id_of_the_div").remove();
}

UPDATE: Your updated question throws off my original answer. 更新:您更新的问题抛弃了我原来的答案。 But let me include the updated answer here first (and then clean-up afterwards). 但是,我先在这里包括更新后的答案(然后再进行清理)。 So the reason you are having a null reference error is because you are not returning the model: 所以你有一个空引用错误的原因是因为你没有返回模型:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM