从没有Ajax的控制器返回asp.net MVC中的警报/消息?(Return alert/message in asp.net MVC from controller without Ajax?)

编程入门 行业动态 更新时间:2024-10-26 12:21:53
从没有Ajax的控制器返回asp.net MVC中的警报/消息?(Return alert/message in asp.net MVC from controller without Ajax?)

在我的应用程序中,如果有人没有成功登录,我想接收并返回类似JavaScript警报的信息以通知他们。 问题是我无法使用Ajax调用来返回此JavaScript警报。 有没有其他的方式来返回某种排序或警报或消息?

In my application if someone does not log in successfully I want to take and return something like a JavaScript alert to notify them. The problem is I can not use a Ajax call to return this JavaScript alert. Is there any other way to return some sort or alert or message?

最满意答案

您可以将消息存储在TempData中(在控制器内的错误情况下)。 然后返回一个视图来显示。

public const string FlashMessageTempDataKey = "_flash"; controller.TempData[FlashMessageTempDataKey] = "The Message (Grandmaster Flash and the Furious Five)";

然后检查TempData是否存在于您的视图中。

public static MvcHtmlString Flash(this HtmlHelper helper) { var message = helper.ViewContext.Controller.TempData[FlashMessageTempDataKey] as string; var sb = new StringBuilder(); if (message != null) { sb.AppendLine("<script>"); sb.AppendLine("$(function() {"); sb.AppendFormat("flash('{0}');", HttpUtility.JavaScriptStringEncode(message)); sb.AppendLine("});</script>"); } return MvcHtmlString.Create(sb.ToString()); }

使用这种扩展方法作为@Html.Flash() ,例如在_layout.cshtml中。 它假定在​​页面上有一些全局的JS函数flash(message)和jQuery来显示消息。

function flash(message) { alert(message); }

请注意,通过这种机制,消息将显示在用户加载的下一个页面上,而这不一定是触发错误的页面(例如,如果他有多个浏览器选项卡打开)。

You can store the message to be shown in the TempData (inside your controller in the error case). Then return a view to be shown.

public const string FlashMessageTempDataKey = "_flash"; controller.TempData[FlashMessageTempDataKey] = "The Message (Grandmaster Flash and the Furious Five)";

And then check whether the TempData is present in your view.

public static MvcHtmlString Flash(this HtmlHelper helper) { var message = helper.ViewContext.Controller.TempData[FlashMessageTempDataKey] as string; var sb = new StringBuilder(); if (message != null) { sb.AppendLine("<script>"); sb.AppendLine("$(function() {"); sb.AppendFormat("flash('{0}');", HttpUtility.JavaScriptStringEncode(message)); sb.AppendLine("});</script>"); } return MvcHtmlString.Create(sb.ToString()); }

Use this extension method as @Html.Flash(), e.g. in your _layout.cshtml. It assumes that there is some global JS function flash(message) and jQuery available on the page to display the message.

function flash(message) { alert(message); }

Note that with this mechanism, the message will be shown on the next page the user loads, which must not necessarely be the page that triggered the error (e.g. if he has multiple browser tabs open).

更多推荐

本文发布于:2023-08-08 01:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466733.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警报   控制器   消息   net   Ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!