大佬教程收集整理的这篇文章主要介绍了jquery – 在MVC中提供用户通知/确认的推荐方法是什么?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
例如,假设用户提供反馈表单的反馈,然后单击“提交反馈”.您可能需要在执行某些验证后显示“感谢您的反馈”消息,例如他们在数据库中有一个有效的电子邮件.一些伪代码:
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!</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或没有?有没有更好的办法?
请扩充我的编码模式!
<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() %>
以上是大佬教程为你收集整理的jquery – 在MVC中提供用户通知/确认的推荐方法是什么?全部内容,希望文章能够帮你解决jquery – 在MVC中提供用户通知/确认的推荐方法是什么?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。