namespace HelperMethods.Controllers {
publicclass HomeController : Controller {
public ActionResult Index() {
ViewBag.Fruits = newstring[] { "Apple", "Orange", "Pear" };
ViewBag.Cities = newstring[] { "New York", "London", "Paris" };
string message = "This is an HTML element: ";
return View((object)message);
}
public ActionResult CreatePerson() {
return View(new Person { Role = Role.Guest});
}
[HttpPost]
public ActionResult CreatePerson(Person person) {
return View("DisplayPerson", person);
}
}
}
内联帮助函数
我们可以直接在视图中定义内联的帮助函数,使用@helper标记内联函数定义:
@model string
@{
Layout = null;
}
@helper ListArrayItems(string[] items)
{
foreach (string str in items)
{
b>@str b>
}
}
DOCTYPE html>html>head>meta name="viewport" content="width=device-width"/>title>Indextitle>head>body>div>
Here are the fruits: @ListArrayItems(ViewBag.Fruits)
div>div>
Here are the cities: @ListArrayItems(ViewBag.Cities)
div>div>
Here is the message:
p>@Modelp>div>body>html>
@model string
@using HelperMethods.Infrastructure
@{
Layout = null;
}
DOCTYPE html>html>head>meta name="viewport" content="width=device-width"/>title>Indextitle>head>body>div>
Here are the fruits: @Html.ListArrayItems((string[])ViewBag.Fruits)
div>div>
Here are the cities: @Html.ListArrayItems((string[])ViewBag.Cities)
div>div>
Here is the message:
p>@Modelp>div>body>html>
public ActionResult Index() {
string message = "This is an HTML element: ";
return View((object)message);
}
在视图中直接输出这个字符串:
@model string
@{
Layout = null;
}
DOCTYPE html>html>head>title>Indextitle>head>body>p>This is the content from the view:p>div>
Here is the message:
p>@Modelp>div>body>html>
最后Razor输出的结果是:
...
div>
Here is the message:
p>This is an HTML element: <input>p>div>
...
publicstatic MvcHtmlString DisplayMessage(this HtmlHelper html, string msg) {
string result = String.Format("This is the message:
{0}
", msg);
returnnew MvcHtmlString(result);
}
视图文件中调用这个帮助函数输出HTML标记:
p>This is the content from the helper method:p>div style="border: thin solid black; padding: 10px">
@Html.DisplayMessage("This is an HTML element: input>")
div>
public staticstring DisplayMessage(this HtmlHelper html, string msg) {
return String.Format("This is the message:
{0}
","This is an HTML element: "); }
这时候字符串又会被HTML编码,不会输出input标签。但这样的结果是
标记也会被HTML编码,这不是我们想要的结果,正确的做法是:
publicstatic MvcHtmlStringDisplayMessage(this HtmlHelper html) {
string encodedMessage = html.Encode("This is an HTML element: ");
string result = String.Format("This is the message:
div class="dataElem">label>Rolelabel>
@Html.DropDownListFor(m => m.Role, new SelectList(Enum.GetNames(typeof(HelperMethods.Models.Role))))
div>
HelperMethods.Models.Role是一个C#的枚举类型,输出的结果是:
div class="dataElem">label>Rolelabel>select data-val="true" data-val-required="The Role field is required." id="Role" name="Role">option selected="selected">Adminoption>option>Useroption>option>Guestoption>select>div>