Reputation: 58962
I'm building a site where i need to be able to notify a user on each page. The function is going to look alot like what StackOverflow is using, the yellow(orange?) border at the top. I dont want to reproduce this logic inside all of my actions. DRY.
I'm thinking about using a action filter, but since i need to query my data layer it does not seem to be the best way to solve it.
So, for example, what would be the best way to implement a feauture like "You have a question with bounty ending in X days" on each page?
Upvotes: 0
Views: 337
Reputation: 14229
When I have logic that needs to go on every action, that needs to initialise view data, I do this in my OnResultExecuting method (called after action runs, before view rendered) of my base controller (from which all my controllers inherit), which sets data on my base view data model (from which all my view data models inherit):
public class BaseViewData
{
public string UserMessage { get; set; }
}
public class BaseController : Controller
{
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
ViewResult viewResult = filterContext.ActionResult as ViewResult;
//Only continue if action returned an ActionResult of type ViewResult,
//and that ViewResults ViewData is of type BaseViewData
if(viewResult != null && viewResult.ViewData is BaseViewData)
{
((BaseViewData)viewResult.ViewData).UserMessage = userService.GetUserMessage();
}
}
}
Upvotes: 1
Reputation: 42158
I would use TempData to store the message, add a helper to render the message (if there is one), and then use that in your master page. This is basically how rails does it, and I have always felt the lack of a notification system (like flash) was an odd gap in ASP.net MVC, just because it is so easy to do.
Upvotes: 0
Reputation: 1038720
In ASP.NET MVC 2 there's the Html.RenderAction. For ASP.NET MVC 1.0 if I recall correctly there's the same functionality in MvcContrib.
Upvotes: 1