C# 从控制器到视图的成功消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18337914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:58:43  来源:igfitidea点击:

Success message from Controller to View

c#asp.netasp.net-mvc-4notifications

提问by Guilherme Oderdenge

The goal

目标

I want to display in my view some message when some user is added.

我想在添加一些用户时在我的视图中显示一些消息。

The problem

问题

When something goes wrong in our model, there is a method (ModelState.AddModelError) to handle unsuccessful messages. But, when the things go okay, how can we handle a message to the user saying that his action was a success?

当我们的模型出现问题时,有一个方法 ( ModelState.AddModelError) 来处理不成功的消息。但是,当一切顺利时,我们如何处理给用户说他的操作成功的消息?

I found this threadthat provides a solution, but about three years passed and I need to know: there's not another way, perhaps more mature? Not that this is not, but we still deal with messages of success on this same way?

我发现这个线程提供了一个解决方案,但大约三年过去了,我需要知道:没有另一种方法,也许更成熟?不是这不是,但我们仍然以同样的方式处理成功的信息?

采纳答案by Mister Epic

There are a few ways to skin this cat. You could use the ViewBag:

有几种方法可以给这只猫剥皮。您可以使用 ViewBag:

ViewBag.SuccessMessage = "<p>Success!</p>";

Then in your view you could render it to the page:

然后在您的视图中,您可以将其渲染到页面:

@ViewBag.SuccessMessage

I'm not a fan of the ViewBag, so I typically have a ViewModel object created that holds all the data I would need for my particular view. And a success message would be just that kind of data:

我不是 ViewBag 的粉丝,所以我通常会创建一个 ViewModel 对象,其中包含我的特定视图所需的所有数据。成功信息就是这样的数据:

public MyViewModel{
    public bool IsSuccess {get;set;}
}

Then in your controller, you would pass this ViewModel to your stongly-typed view

然后在您的控制器中,您将此 ViewModel 传递给您的强类型视图

[HttpPost]
public ActionResult Update(MyViewModel vm){
    //Glorious code!

   return View(vm)
}

Finally, just check it in your view and print a message if it succeeds:

最后,只需在您的视图中检查它并在成功时打印一条消息:

@if(vm.IsSuccess){
     <p>Here is an amazing success message!</p>
}

Also, instead of that, you can use TempData, which works like the ViewBag but only lasts until the end of your next request and is then discarded:

此外,您可以使用 TempData 代替它,它的工作方式与 ViewBag 类似,但仅持续到下一个请求结束,然后被丢弃:

TempData["SuccessMessage"] = "Success!";

回答by dotnethaggis

TempData

Use MVC TempData - TempData

使用 MVC TempData - TempData

It's only available for that page request. Which is perfect for success messages etc.

它仅适用于该页面请求。这非常适合成功消息等。

回答by asymptoticFault

A good solution for this is the TempDatacollection. Its values are cleared at the end of the request which makes it ideal for one time messages like informing the user that something was successful.

一个很好的解决方案是TempData集合。它的值在请求结束时被清除,这使得它非常适合一次性消息,例如通知用户某事已成功。

Controller

控制器

TempData["Message"] = "Operation successful!";

View

看法

@TempData["Message"]

And yes, this is still currently the best approach.

是的,这仍然是目前最好的方法。

回答by D Stanley

Conceptually, I think the answer still holds. If the message is an integral part of the view, it should be part of the ViewModel. TempDatais a shortcut for passing data without modifying the ViewModeldefinition, which some people frown upon.

从概念上讲,我认为答案仍然成立。如果消息是视图的组成部分,则它应该是ViewModel. TempData是一种传递数据而不修改ViewModel定义的快捷方式,有些人对此不屑一顾。

回答by Brad Christie

TempDataisn't a bad way to hand one-offs to the UI for the purposes of notifying the user. The great part about them is they persist between action calls, but are removed once they're read. So, in the case of just handing off a "it worked" message, it works great.

TempData出于通知用户的目的,将一次性交给 UI 是一种不错的方式。关于它们的重要部分是它们在操作调用之间持续存在,但一旦被读取就会被删除。因此,在只是传递“有效”消息的情况下,效果很好。

You can tie them in several ways, but I'll give you a general example to get you going:

您可以通过多种方式将它们联系起来,但我会举一个通用示例来帮助您:

public static class NotificationExtensions
{
    private const String NotificationsKey = "MyApp.Notifications";

    public static void AddNotification(this ControllerBase controller, String message)
    {
        ICollection<String> messages = controller.TempData[NotificationsKey] as ICollection<String>;
        if (messages == null)
        {
            controller.TempData[NotificationsKey] = (messages = new HashSet<String>());
        }
        messages.Add(message);
    }

    public static IEnumerable<String> GetNotifications(this HtmlHelper htmlHelper)
    {
        return htmlHelper.ViewContext.Controller.TempData[NotificationsKey] as ICollection<String> ?? new HashSet<String>();
    }
}

Now in your action you can call this.AddNotification("User successfully added!");and within your view you can display them using:

现在,在您的操作中,您可以调用this.AddNotification("User successfully added!");并在您的视图中使用以下方法显示它们:

@foreach (String notification in Html.GetNotifications())
{
    <div class="notification">
        <p>@notification/p>
        <i class="icon-close"></i>
    </div>
}

(...Or something similar) which could be effectively placed in your main view and used as a general notification method for any action performed. (Almost like how StackOverflow has the gold bar at the top of the page during certain events).

(...或类似的东西)可以有效地放置在您的主视图中,并用作执行任何操作的通用通知方法。(几乎就像 StackOverflow 在某些事件期间页面顶部的金条一样)。

回答by Carrie Kendall

Expanding from Brad Christie'sanswer, I created a NuGet package, BootstrapNotifications, that will do this for you with built-in Bootstrap3 support. This package also supports multiple notification types (error, warning, success, and info) with pre-styled alerts and is easily extendable.

扩展Brad Christie 的回答,我创建了一个 NuGet 包BootstrapNotifications,它将通过内置的 Bootstrap3 支持为您执行此操作。这个包还支持多种通知类型(错误、警告、成功和信息)和预先设计的警报,并且很容易扩展。

The extension supports multiple notifications per request of the same type and different types elegantly.

该扩展优雅地支持同一类型和不同类型的每个请求的多个通知。

The Code

编码

NotificationExtensions.cs:

NotificationExtensions.cs

public static class NotificationExtensions
{
    private static IDictionary<String, String> NotificationKey = new Dictionary<String, String>
    {
        { "Error",      "App.Notifications.Error" }, 
        { "Warning",    "App.Notifications.Warning" },
        { "Success",    "App.Notifications.Success" },
        { "Info",       "App.Notifications.Info" }
    };


    public static void AddNotification(this ControllerBase controller, String message, String notificationType)
    {
        string NotificationKey = getNotificationKeyByType(notificationType);
        ICollection<String> messages = controller.TempData[NotificationKey] as ICollection<String>;

        if (messages == null)
        {
            controller.TempData[NotificationKey] = (messages = new HashSet<String>());
        }

        messages.Add(message);
    }

    public static IEnumerable<String> GetNotifications(this HtmlHelper htmlHelper, String notificationType)
    {
        string NotificationKey = getNotificationKeyByType(notificationType);
        return htmlHelper.ViewContext.Controller.TempData[NotificationKey] as ICollection<String> ?? null;
    }

    private static string getNotificationKeyByType(string notificationType)
    {
        try
        {
            return NotificationKey[notificationType];
        }
        catch (IndexOutOfRangeException e)
        {
            ArgumentException exception = new ArgumentException("Key is invalid", "notificationType", e);
            throw exception;
        }
    }
}

public static class NotificationType
{
    public const string ERROR = "Error";
    public const string WARNING = "Warning";
    public const string SUCCESS = "Success";
    public const string INFO = "Info";

}

_Notifications.cshtml:

_Notifications.cshtml:

@using YourApp.Extensions
@{
    var errorList = Html.GetNotifications(NotificationType.ERROR);
    var warningList = Html.GetNotifications(NotificationType.WARNING);
    var successList = Html.GetNotifications(NotificationType.SUCCESS);
    var infoList = Html.GetNotifications(NotificationType.INFO);
}
<!-- display errors -->
@if (errorList != null)
{
    <div class="alert alert-danger alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        @if(errorList.Count() > 1){
            <strong><span class="glyphicon glyphicon-remove"></span> There are @errorList.Count() errors: </strong>
            <ul>
                @foreach (String message in errorList)
                {
                    <li>@Html.Raw(message)</li>
                }
            </ul>
        }
        else{
            <strong><span class="glyphicon glyphicon-remove"></span> Error: </strong>
            @Html.Raw(errorList.First())
        }
    </div>
}

<!-- display warnings -->
@if (warningList != null)
{
    <div class="alert alert-warning alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        @if(warningList.Count() > 1){
            <strong><span class="glyphicon glyphicon-warning-sign"></span> There are @warningList.Count() warnings: </strong>
            <ul>
                @foreach (String message in warningList)
                {
                    <li>@Html.Raw(message)</li>
                }
            </ul>
        }
        else{
            <strong><span class="glyphicon glyphicon-warning-sign"></span> Warning: </strong>
            @Html.Raw(warningList.First())
        }
    </div>
}

<!-- display success -->
@if (successList != null)
{
    <div class="alert alert-success alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        @if(successList.Count() > 1){
            <strong><span class="glyphicon glyphicon-ok"></span> There are @successList.Count() successful notifications: </strong>
            <ul>
                @foreach (String message in successList)
                {
                    <li>@Html.Raw(message)</li>
                }
            </ul>
        }
        else{
            <strong><span class="glyphicon glyphicon-ok"></span> Success! </strong>
            @Html.Raw(successList.First())
        }
    </div>
}

<!-- display success -->
@if (infoList != null)
{
    <div class="alert alert-info alert-dismissable">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        @if(infoList.Count() > 1){
            <strong><span class="glyphicon glyphicon-info-sign"></span> There are @infoList.Count() notifications: </strong>
            <ul>
                @foreach (String message in infoList)
                {
                    <li>@Html.Raw(message)</li>
                }
            </ul>
        }
        else{
            <strong><span class="glyphicon glyphicon-info-sign"></span> </strong>
            @Html.Raw(infoList.First())
        }
    </div>
}

To see all of this code and how its used, you can download a full working demo from github.

要查看所有这些代码及其使用方式,您可以从github下载完整的工作演示。