In ASP.NET MVC, you have ViewBag , ViewData and TempData at your disposal (see this blog post for more information). ViewBag is a dynamic wrapper around the ViewData dictionary. If you execute ViewBag.Prop = "value" , this is equivalent to ViewData["Prop"] = "value" . When you use the Model property in a view, you get ViewData.Model . See for yourself:
public abstract class WebViewPage<TModel> : WebViewPage { private ViewDataDictionary<TModel> _viewData; public new AjaxHelper<TModel> Ajax { get; set; } public new HtmlHelper<TModel> Html { get; set; } public new TModel Model { get { return ViewData.Model; } } }
We can reach your end using ViewBag or ViewData to preserve your special properties. The first step is to create custom WebViewPage<TModel> output with the desired property:
public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel> { public IList<string> Messages { get { return ViewBag.Messages ?? (ViewBag.Messages = new List<string>()); } } }
Now go to your view and replace the @model YourModelClass line (first line) with the following:
@inherits CustomWebViewPage<YourModelClass>
Now you can use the Messages property in your view.
@String.Join(", ", Messages)
To use it in your controllers, you probably want to get from Controller and add a property there.
public abstract class CustomControllerBase : Controller { public IList<string> Messages { get { return ViewBag.Messages ?? (ViewBag.Messages = new List<string>()); } } }
Now, if you exit this controller, you can use your new property. Everything that you specify in the list will also be available to you in the view.
public class ExampleController : CustomControllerBase { public ActionResult Index() { Messages.Add("This is a message"); return View(); } }
I used the ViewBag because it made the getter property shorter. You can do the same with ViewData if you want ( ViewData["Messages"] ).
This is not exactly the same as that implemented by Model , because someone may accidentally overwrite your property if they use a key that you save, but it is close enough to be functionally equivalent if you just make sure to use a unique the key.
If you dig deeper, you can get from ViewDataDictionary and place your property there, and then override some of the controller and view methods to use it instead. Then your property will be exactly the same as Model . But I will leave it to you - I do not think it is worth it.