当前位置 : 主页 > 网页制作 > JQuery >

jquery – 在MVC中提供用户通知/确认的推荐方法是什么?

来源:互联网 收集:自由互联 发布时间:2021-06-15
我遇到的一个常见情况是在用户执行操作以通知他们成功后向用户提供通知/确认. 例如,假设用户提供反馈表单的反馈,然后单击“提交反馈”.您可能需要在执行某些验证后显示“感谢您
我遇到的一个常见情况是在用户执行操作以通知他们成功后向用户提供通知/确认.

例如,假设用户提供反馈表单的反馈,然后单击“提交反馈”.您可能需要在执行某些验证后显示“感谢您的反馈”消息,例如他们在数据库中有一个有效的电子邮件.一些伪代码:

public ActionResult SubmitFeedback(string Feedback, int UserID)
{
    MyDataContext db = new DataContext()

    if(db.usp_HasValidEmail(UserID)) //Check user has provided a valid email
        return View("Index"); //Return view and display confirmation
    else
        ModelState.AddModelError("InvalidEmail", "We do not hold an email record for you. Please add one below");
        return View("Index);
}

我理解如何使用Html.ValidationMessage等验证条目.这很好,我通常检查无效的条目,无论是在客户端使用jQuery还是在我的Action早期(即在我开始访问数据库之前)并退出我的操作,如果有是无效的条目.

但是,所有条目都有效并且您想要显示确认消息的情况如何?

选项1:拥有完全独立的视图

这似乎违反了DRY原则,通过使用全新的View(和ViewModel)来显示几乎相同的信息,期望用户通知.

选项2:视图中的条件逻辑

在这种情况下,我可以在View中有一个条件语句,用于检查SubmitFeedback Action中传递的某些TempData是否存在.再次,伪代码:

<% if(TempData["UserNotification"] != null {%>
   <div class="notification">Thanks for your Feedback&#33;</div>
   <% } %>

选项3:使用jQuery检查页面加载时的TempData

在这种情况下,我将有一个隐藏字段,我将通过SubmitFeedback Action填充TempData.然后我会使用jQuery来检查隐藏的字段值.更多伪代码:

<%=Html.Hidden("HiddenField", TempData["UserNotification"])%> //in View

$(document).ready(function() {
    if ($("input[name='HiddenField']").length > 0)
        $('div.notification').show();
        setTimeout(function() { $('div.notification').fadeOut(); }, 3000);
});

我对此的初步想法是:

>选项1:完全分离视图,但看起来有点过分和低效(违反DRY)
>选项2:足够简单,但在视图中有条件逻辑(我不会为了这个而在MVC祭坛上牺牲?!?)
>选项3:感觉它过于复杂.它确实避免了View中的逻辑.

怎么说你?选项1,2,3或没有?有没有更好的办法?

请扩充我的编码模式!

我喜欢选项1.此外,您不需要条件,它适用于禁用的JavaScript.只需将其粘贴在母版页中的某个位置即可:

<div class="notification">
    <%= Html.Encode(TempData["Notification"]) %>
</div>

您当然可以通过使用一些很好的插件(例如jGrowl或Gritter)或甚至查看how StackOverflow does it来逐步增强/动画.

另一个解决方案是编写一个可能是最好的帮助器:

public static class HtmlExtensions
{
    public static MvcHtmlString Notification(this HtmlHelper htmlHelper)
    {
        // Look first in ViewData
        var notification = htmlHelper.ViewData["Notification"] as string;
        if (string.IsNullOrEmpty(notification))
        {
            // Not found in ViewData, try TempData
            notification = htmlHelper.ViewContext.TempData["notification"] as string;
        }

        // You may continue searching for a notification in Session, Request, ... if you will

        if (string.IsNullOrEmpty(notification))
        {
            // no notification found
            return MvcHtmlString.Empty;
        }

        return FormatNotification(notification);
    }

    private static MvcHtmlString FormatNotification(string message)
    {
        var div = new TagBuilder("div");
        div.AddCssClass("notification");
        div.SetInnerText(message);
        return MvcHtmlString.Create(div.ToString());
    }

}

然后在你的主人:

<%= Html.Notification() %>
网友评论