[英]Display text from the controller
我需要在controller
的view
显示一条消息。 这是我的代码;
视图
@Html.LabelFor // How do i write the rest to display the message
控制器
public ActionResult Index(MyModel model)
{
// I Need to send a String to the Label in the View
return View();
}
可以说,至少在需要时,更优雅的解决方案是使用强类型视图(带有模型-MVC中的M)。 一个简单的例子可能是:
该模型:
public class MessageViewModel
{
public string Message {get; set;}
}
控制器:
public ActionResult Index()
{
var viewModel = new MessageViewModel {Message = "Hello from far away"};
return View(viewModel);
}
风景:
@model MyNamespace.MessageViewModel
<h2>@Html.DisplayFor(model => model.Message)</h2>
我是否会为页面上的单个消息而烦恼? 出乎意料的是,我大多数时候都会。 该视图有一些优雅之处,它确切地知道了预期的结果(反之亦然),Intellisense支持以及HtmlHelper
的DisplayFor()
方法,您可以在其中进行各种隐式格式化。
话虽这么说,“最简单”(阅读:快速又肮脏,但是很快就很难看)解决方案是将您的消息填充到ViewBag
动态对象中。
在控制器中:
ViewBag.MyMessage = "Hello from a far away place";
在视图中:
@ViewBag.MyMessage
但是这样做会损失Intellisense,可重复性(DRY),甚至可能失去理智。 可能在一个地方使用了一个属性( 一个 ViewBag.Title
,默认_Layout页面使用的标题)。 一堆未连接的物品塞满了袋子,不,谢谢。
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>
public ActionResult Index(MyModel model)
{
ViewBag.Message = "Hello World";
return View();
}
您的看法
<h1>@ViewBag.Message</h1>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.