【问题标题】:Adding a success message after deleting item, in MVC4在 MVC4 中删除项目后添加成功消息
【发布时间】:2012-09-19 15:22:47
【问题描述】:

我在屏幕上显示了一个删除超链接:

用户部分视图:

<%: Ajax.ActionLink("Delete", "Delete", new { id = item.UserID }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "tabs-users", InsertionMode = InsertionMode.Replace }, htmlAttributes: new { data_target = "#tabs-users" })%>

这会在我的控制器中调用一个方法

控制器

    [HttpGet]
    public PartialViewResult Delete(int id)
    {
        userManager.DeleteUser(id);
        ViewBag.Status = string.Format("User deleted ok, id: {0}", id);
        return PartialView("UsersPartial", userManager.GetUsers());
    }

在上面的代码中,我返回了一个 PartialView,这是可行的。我还想在这个视图的顶部显示一条消息,上面在 ViewBag.Status 中定义,但我只希望它在执行此操作后显示此 div。

还要注意,我要返回的视图是强类型的:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<LMS.Data.User>>" %>

最后,我要显示的状态消息是一个 div,它是我在另一个局部视图中创建的,因此我可以在整个站点中显示它。

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>

<div id="status" class="statusok">
<%: ViewBag.Status %>
</div>

这样做的正确方法是什么?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-ajax


    【解决方案1】:

    ViewBag.Status 在您为其分配值之前将为空,因此您可以在视图中对其进行检查然后显示它:

    @if(ViewBag.Status != null)
    {
        <div id="status" class="statusok">
           @ViewBag.Status
        </div>
    }
    

    在返回相同视图的后续调用中,如果您不再希望它显示,只需将 ViewBag.Status 设置为 null

    【讨论】:

    • 谢谢,这确实对我有所帮助,但是,另一个答案更完整,并回答了“最佳”方法。不过,我相信我将来会使用你的答案,所以谢谢。
    【解决方案2】:

    您不能从控制器操作返回 2 个不同的局部视图。您可能使用的一种方法是 render the first partial to a string 然后让您的控制器操作返回具有 2 个属性的 JSON 结果 - 一个包含 HTML 部分,另一个包含要显示的消息:

    [HttpDelete]
    public PartialViewResult Delete(int id)
    {
        userManager.DeleteUser(id);
        return Json(new 
        {
            Partial = RenderPartialViewToString("UsersPartial", userManager.GetUsers()),
            StatusMessage = string.Format("User deleted ok, id: {0}", id)
        });
    }
    

    然后:

    <%= Ajax.ActionLink(
        "Delete", 
        "Delete", 
        new { 
            id = item.UserID 
        }, 
        new AjaxOptions { 
            HttpMethod = "DELETE", 
            OnSuccess = "onDelete"
        }, 
        htmlAttributes: new { data_target = "#tabs-users" }
    ) %>
    

    然后编写onDelete回调:

    function onDelete(result) {
        $('#tabs-users').html(result.Partial);
    
        // TODO: instead of alerting display the message wherever you want
        // and using whatever plugin you want to make it look pretty
        alert(result.StatusMessage);
    }
    

    您还会注意到,我为此任务使用了正确的 HTTP 动词 - 删除。切勿使用 GET 动词来调用正在修改服务器上的状态的控制器操作(例如删除实体)。

    【讨论】:

    • 谢谢,这正是我想要的。感谢您对动词的提示,直到您指出它才注意到。从 webforms 到 mvc,我还有很多东西要学。谢谢!
    猜你喜欢
    • 2018-05-18
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多