I need to display a message in the view from the controller. Here’s my code;
VIEW
@Html.LabelFor // How do i write the rest to display the message
CONTROLLER
public ActionResult Index(MyModel model)
{
// I Need to send a String to the Label in the View
return View();
}
Arguably the more elegant solution, when called for at least, is to use a strongly-typed view (with a model – the M in MVC). A simple example could be:
The model:
The controller:
The view:
Would I bother with this for a single message on a page? Surprisingly, most of the time I would. There’s something elegant about the view knowing exactly what to expect (and vice versa), Intellisense support, and the
HtmlHelper‘sDisplayFor()method where you can do all kinds of implicit formatting.That being said, the “simplest” (read: quick and dirty, but gets ugly quick) solution would be to stuff your message into the
ViewBagdynamic object.In the controller:
In the view:
But doing this, you lose Intellisense, repeatability (DRY), and possibly your sanity. One property used in one place, maybe (a la
ViewBag.Titlethat the default _Layout page uses). A whole bunch of disconnected objects stuffed in the bag, no thank you.