Reputation: 9850
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();
}
Upvotes: 0
Views: 3407
Reputation: 116498
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:
public class MessageViewModel
{
public string Message {get; set;}
}
The controller:
public ActionResult Index()
{
var viewModel = new MessageViewModel {Message = "Hello from far away"};
return View(viewModel);
}
The view:
@model MyNamespace.MessageViewModel
<h2>@Html.DisplayFor(model => model.Message)</h2>
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
's DisplayFor()
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 ViewBag
dynamic object.
In the controller:
ViewBag.MyMessage = "Hello from a far away place";
In the view:
@ViewBag.MyMessage
But doing this, you lose Intellisense, repeatability (DRY), and possibly your sanity. One property used in one place, maybe (a la ViewBag.Title
that the default _Layout page uses). A whole bunch of disconnected objects stuffed in the bag, no thank you.
Upvotes: 1
Reputation: 7752
public ActionResult Index(MyModel model)
{
ViewBag.Message = "Hello World";
return View();
}
Your view
<h1>@ViewBag.Message</h1>
Upvotes: 0
Reputation:
You can use Viewbag or viewdata in your controller
public ActionResult Index()
{
ViewData["listColors"] = colors;
ViewData["dateNow"] = DateTime.Now;
ViewData["name"] = "Hajan";
ViewData["age"] = 25;;
ViewBag.ListColors = colors; //colors is List
ViewBag.DateNow = DateTime.Now;
ViewBag.Name = "Hajan";
ViewBag.Age = 25;
return View();
}
<p>
My name is
<b><%: ViewData["name"] %></b>,
<b><%: ViewData["age"] %></b> years old.
<br />
I like the following colors:
</p>
<ul id="colors">
<% foreach (var color in ViewData["listColors"] as List<string>){ %>
<li>
<font color="<%: color %>"><%: color %></font>
</li>
<% } %>
</ul>
<p>
<%: ViewData["dateNow"] %>
</p>
Upvotes: 0