MVC---Help Methods

<strong>一. 创建自定义Help Method</strong>

@model string
@{
    Layout = null;
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-w idth" />
    <title>Index</title>
</head>
<body>
    <div>
        Here are the fruits:
        @foreach (string str in (string[])ViewBag.Fruits)
        {
            <b>@str </b>
        }
    </div>
    <div>
        Here are the cities:
        @foreach (string str in (string[])ViewBag.Cities)
        {
            <b>@str </b>
        }
    </div>
    <div>
        Here is the message:
        <p>@Model</p>
    </div>
</body>
</html>

<strong>1.1 创建内联(Inline)的Help Method</strong>

@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-w idth" />
    <title>Index</title>
</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>@Model</p>
    </div>
</body>
</html>

内联Help Method看上去是一个方法,但是没有返回值。

<strong>1.2 创建外部的Help Method</strong>

    public static class CustomHelpers
    {
        public static MvcHtmlString ListArrayItems(this HtmlHelper html, string[] list)
        {
            TagBuilder tag = new TagBuilder("ul");
            foreach (string str in list)
            {
                TagBuilder itemTag = new TagBuilder("li");
                itemTag.SetInnerText(str);
                tag.InnerHtml += itemTag.ToString();
            }
            return MvcHtmlString.Create(tag.ToString());
        }
    }

this关键字说明定义的是一个扩展方法,HtmlHelper类型的实例能够提供很多内容,如Controller,View,RouteData等。
TagBuilder常用的成员有:
InnerHtml
SetInnerText(string)
AddCssClass(string)
MergeAttribute(string, string, bool)

使用自定义的外部Help Method:

@model string
@using HelperMethods.Infrastructure
@{
    Layout = null;
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-w idth" />
    <title>Index</title>
</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>@Model</p>
    </div>
</body>
</html>

<strong>1.3 管理HelpMethods中的字符串编码</strong>
处于安全性考虑,需要防止数据被浏览器解释成标记。
必须对Help Methods的内容进行编码。
解决方式是使用Encode方法:

        public static MvcHtmlString DisplayMessage(this HtmlHelper html, string msg)
        {
            // msg值为: This is an Html element:<input>
            string encodeMessage = html.Encode(msg);
            string result = string.Format("This is th message:<p>{0}<p>", encodeMessage);
            return new MvcHtmlString(result);
        }

<strong>1.4 使用内建的Form Help Methods</strong>
<strong>1.4.1 创建Form元素</strong>
标准的表单如下:

   <form action="/Home/CreatePerson" method="post">
        <div class="dataElem">
            <label>PersonId</label>
            <input name="personId" value="@Model.PersonId" />
        </div>
        <div class="dataElem">
            <label>First Name</label>
            <input name="FirstName" value="@Model.FirstName" />
        </div>
        <div class="dataElem">
            <label>Last Name</label>
            <input name="lastName" value="@Model.LastName" />
        </div>
        <input type="submit" value="Submit" />
    </form>

使用Help Methods:

@using (Html.BeginForm())
{
    <div class="dataElem">
        <label>PersonId</label>
        <input name="personId" value="@Model.PersonId" />
    </div>
    <div class="dataElem">
        <label>First Name</label>
        <input name="FirstName" value="@Model.FirstName" />
    </div>
    <div class="dataElem">
        <label>Last Name</label>
        <input name="lastName" value="@Model.LastName" />
    </div>
    <input type="submit" value="Submit" />
}

BeginForm有多个重载方法:

@using (Html.BeginForm("CreatePerson", "Home", 
    new { id = "MyIdValue" }, FormMethod.Post, 
    new { @class = "personClass", data_fromType = "person" }))
{
    <div class="dataElem">
        <label>PersonId</label>
        <input name="personId" value="@Model.PersonId" />
    </div>
    <div class="dataElem">
        <label>First Name</label>
        <input name="FirstName" value="@Model.FirstName" />
    </div>
    <div class="dataElem">
        <label>Last Name</label>
        <input name="lastName" value="@Model.LastName" />
    </div>
    <input type="submit" value="Submit" />
}

调用上述BeginForm所产生的HTML的form标签为:

<form action="/Home/CreatePerson/MyIdValue" class="personClass" data-fromType="person" method="post"

<strong>1.4.2 指定Form使用的路由</strong>
首先在RouteConfig中加入一条路由:

routes.MapRoute(name: "FormRoute", url: "app/forms/{controller}/{action}");

如果需要确保使用特定的一条路由:

@using (Html.BeginRouteForm("FormRoute", 
new { }, 
FormMethod.Post, 
new { @class = "personClass", data_formType = "person" }))
{
}

产生的form标签为:

<form action="/app/forms/Home/CreatePerson" class="personClass" data-formType="person" method="post">

<strong>1.4.3 使用Input Helper</strong>

Input Html Helper.png
@using (Html.BeginRouteForm("FormRoute", new { }, FormMethod.Post, new { @class = "personClass", data_formType = "person" }))
{
    <div class="dataElem">
        <label>PersonId</label>
        @*<input name="personId" value="@Model.PersonId" />*@
        @Html.TextBox("personId", @Model.PersonId)
    </div>
    <div class="dataElem">
        <label>First Name</label>
        @Html.TextBox("firstName", @Model.FirstName)
    </div>
    <div class="dataElem">
        <label>Last Name</label>
        @*<input name="lastName" value="@Model.LastName" />*@
        @Html.TextBox("lastName", @Model.LastName)
    </div>
    <input type="submit" value="Submit" />
}

上述方法需要保证第一个参数匹配第二个参数。上图中的所有input Helper都对应一个强类型的Helper。

强类型Input Html Helper.png
@using (Html.BeginRouteForm("FormRoute", new { }, FormMethod.Post, new { @class = "personClass", data_formType = "person" }))
{
    <div class="dataElem">
        <label>PersonId</label>
        @*<input name="personId" value="@Model.PersonId" />*@
        @*@Html.TextBox("personId", @Model.PersonId)*@
        @Html.TextBoxFor(m => m.PersonId)
    </div>
    <div class="dataElem">
        <label>First Name</label>
        @*@Html.TextBox("firstName", @Model.FirstName)*@
        @Html.TextBoxFor(m => m.FirstName)
    </div>
    <div class="dataElem">
        <label>Last Name</label>
        @*<input name="lastName" value="@Model.LastName" />*@
        @*@Html.TextBox("lastName", @Model.LastName)*@
        @Html.TextBoxFor(m => m.LastName)
    </div>
    <input type="submit" value="Submit" />
}

<strong>1.4.4 创建Select元素</strong>


Select Html Helper.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,652评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,623评论 18 399
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,079评论 25 707
  • github地址,欢迎大家提交更新。 express() express()用来创建一个Express的程序。ex...
    Programmer客栈阅读 2,522评论 0 1
  • 周六上班,于我不似平常日的忙碌。通常,我会整理资料,清理清洁。往常,我会准备办证资料的复印,归档,且核对每个政府部...
    HAPPY_2019阅读 227评论 0 0