2013-02-18 119 views
0

我需要从controller中显示view中的消息。这是我的代码;显示来自控制器的文本

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(); 
} 
+0

有很多方法,包括ViewBags和ViewData,但令人震惊的是,你也可以使用模型。请做好自己的尝试。这个问题可以很容易回答 – 2013-02-18 17:21:43

回答

1

可以说,更优雅的解决方案至少要求使用强类型视图(使用模型 - 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支持以及可以在其中执行各种隐式格式化的方法HtmlHelperDisplayFor()方法。


话虽这么说,在“简单”(阅读:快速和肮脏的,但得到快速丑)解决方案,将是你的东西邮件到ViewBag动态对象。

在控制器:

ViewBag.MyMessage = "Hello from a far away place"; 

在视图:

@ViewBag.MyMessage 

但这样一来,你输了智能感知,可重复性(干),可能你的理智。在一个地方使用一个属性,也许(a laViewBag.Title即默认的_Layout页面使用)。一大堆断开的东西塞进包里,不用谢了。

+0

如果您删除了关于ViewBag的答案的第一部分,那么您将获得我的+1,指出唯一正确的方法是使用视图模型。 – 2013-02-18 17:31:25

+0

谢谢!我希望有人会提到制作模型。这绝对是一种首选方式。另外,在你之前的编辑中,你有一个字符串模型,并且调用了'return View(“来自远处的Hello”);'。这将失败,因为View(字符串)重载会使用该字符串来查找视图。如果你想用字符串作为你的模型传递默认视图,你需要命名参数:'返回视图(模型:“你好,来自遥远的地方。”);'。 – Joshua 2013-02-18 17:31:25

+0

@Joshua你完全正确,这就是为什么我改变它以保持简单。 – 2013-02-18 17:33:33

0

你可以在你的控制器使用Viewbag或可视数据

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> 
0
public ActionResult Index(MyModel model) 
{ 

     ViewBag.Message = "Hello World"; 

     return View(); 
} 

你的看法

<h1>@ViewBag.Message</h1>