在MVC4中删除项目后添加成功消息

时间:2012-09-19 15:22:47

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

屏幕上显示删除超链接:

UsersPartial VIEW:

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

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

CONTROLLER

    [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>

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

2 个答案:

答案 0 :(得分:3)

在您为其指定值之前,

ViewBag.Status将为null,因此您只需在视图中对其进行检查,然后显示它:

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

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

答案 1 :(得分: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动词执行此任务 - DELETE。切勿使用GET动词来调用正在修改服务器状态的控制器操作(例如删除实体)。

相关问题