2013-05-13 60 views
0

我的服务层向控制器发回一个带有警告/成功/信息/错误消息的DTO,该控制器从基本控制器继承,在此处我以消息方式处理消息。MVC - 自动处理用户通知

我不知道我的执行是否是完全的废话,我真的想要一些建议!

DTO

Public Class ExecutionResult 
    Public Enum AlertType 
     Warning 
     Success 
     Info 
     [Error] 
    End Enum 

    Public Property Type() As AlertType 
    Public Property Message() As String 
End Class 

基地控制器: (与我可以从每一个控制器访问属性executionResult)

Public Class BaseController 
    Inherits System.Web.Mvc.Controller 

    Protected Overloads Overrides Sub OnActionExecuted(ByVal ctx As ActionExecutedContext) 
     Alert() 
    End Sub 

    Public Property executionResult As New ExecutionResult 

    Public Sub Alert() 
     If Not String.IsNullOrWhiteSpace(Me.executionResult.Message) Then 
      TempData.Add(Me.executionResult.Type, Me.executionResult.Message) 
     End If 
    End Sub 
End Class 

控制器:

... 
Inherits BaseController 
... 

Function SomeFunction() As ActionResult 
    executionResult = _service.SomeFunctionInTheServiceLayer(viewModel) 
End Function 

然后我从主页

@For Each item As KeyValuePair(Of String, Object) In TempData 
    If (TempData.ContainsKey(item.Key)) Then 
     @<div class="alert [email protected]"> 
      @item.Value 
     </div>   
    End If 
Next 
+0

如果它适用于你和你对解决方案感到满意,没关系,不是吗? – Kenneth 2013-05-13 08:58:25

+0

只想知道这种情况是否存在“最佳实践”,因为我认为每个人都必须在MVC网络应用程序中以某种方式通知用户。 – stare 2013-05-13 09:02:39

回答

0

显示在一个局部视图中的消息。在第一,因为它依赖于SessionState的具有用于所有控制器合作,以启用我不会用TempData的哪个由于可能的性能下降,因此不是最佳实践。

无论如何,您不必在Session/TempData中存储消息,因为您的视图是作为您的操作的结果呈现的。不需要在请求之间存储消息。所以ViewBag应该足够了。

我想你必须打电话给你的Alert函数的地方? 我会定义存储在ViewBag消息的basecontroller功能(对不起,它在C#):

public void SetAlert(ExecutionResult result) { 
    ViewBag.Alert = result; 
} 

在你看来,你可以简单地访问ViewBag:

@if (ViewBag.Alert != null) { 
    <div class="alert [email protected](ViewBag.Alert.Type)"> 
     @ViewBag.Alert.Message 
    </div>   
} 
+0

感谢您的回复!用RedirectToAction调用不会不可能使用ViewBag?我不需要调用'Alert'函数,因为我拦截了OnActionExecuted,它依赖于在基础控制器中声明的公共属性。 – stare 2013-05-13 09:20:53

+0

是的,这是正确的。如果要在请求之间保留警报,则必须使用某种存储。 – Jan 2013-05-13 09:34:04