这一篇,简单记录下利用Html辅助器生成的常用Web控件。
一.TextBox控件
1.Html.TextBox()
先介绍使用该方法生成文本框,从定义上看,默认有4种方法供我们重载,下面每种我都试一下:
@using HtmlSampleApp.MyManagers;
@model HtmlSampleApp.Models.Sheep
@{
ViewBag.Title = "Index";
}
Index
@{
@Html.TextBox("text1");
@Html.TextBox("text2", "Hello~");
@Html.TextBox("text3", "world", new { id = "mytext1", maxlength = "15", size = "20", background = "Red" });
var dic = new Dictionary();
dic.Add("key1", new { id = "mytext2", maxlength = "15", size = "20", style = "background-color:#FFCCFF", onfocus = "this.value=\"\"" });
@Html.TextBox("text4", "Merry", dic["key1"]);
}
生成的网页如下:
源码:
IndexIndex
2.Html.TextBoxFor
同样 ,该方法也有三个重载,这里都试验一下:
@using HtmlSampleApp.MyManagers;
@model HtmlSampleApp.Models.Sheep
@{
ViewBag.Title = "Index";
}
Index
@{
@Html.TextBoxFor(m => m.name);
@Html.TextBoxFor(m => m.name, new { style = "background-color:blue" });
var dic = new Dictionary();
dic.Add("key1", new { id = "mytext2", maxlength = "15", size = "20", style = "background-color:#FFCCFF", onfocus = "this.value=\"\"" });
@Html.TextBoxFor(m => m.name, dic["key1"]);
}
运行结果:
查看源码:
IndexIndex
总结:
1)Html.TextBox方法可以自动生成textBox的id,name属性,属性值为首参数值。或生成value属性,属性值为第二参数值,或生成其它属性及值,对应第三参数;
2)Html.TextBoxFor方法可以自动生成textBox的id,name属性,属性值为首参数返回的属性名,而不是属性值(如上面的是Sheep的name属性,而不是name的属性值Tom).
生成value属性,属性值为首参数返回的属性的值(如上面的Tom).其它属性及值,对应第二参数。
注意两种方法的其它属性里如果包含了id或name,value参数,会覆盖首参数定义的值。即如果首参数定义了id=“id1”,而object attribute定义了id=“id2”,那么id2会覆盖id1.
二.DropDownList控件
其实,网页中的dropdownlist也就是标签,如:
IndexIndex
item---------1
item---------2
item---------3
它的实际效果是一个下拉框里有3个选项,默认是选中第三个:
同样,可以使用Html.DropDownList及HtmlDropDownList<>方法实现:
1)Html.DropDownList方法
从定义上看,目前默认有8中重载方式,下面取其中具有代表性的方法试验一下,其它大同小异:
@using HtmlSampleApp.MyManagers;
@model HtmlSampleApp.Models.Sheep
@{
ViewBag.Title = "Index";
}
Index
@{
@Html.DropDownList("dropdownlist3",
new List()
{
new SelectListItem { Text="item---------1"},
new SelectListItem { Text="item---------2"},
new SelectListItem { Text="item---------3",Selected=true},
});
@Html.DropDownList("dropdownlist4",
new List()
{
new SelectListItem { Text="item---------1"},
new SelectListItem { Text="item---------2"},
new SelectListItem { Text="item---------3",Selected=true}
},
new { style = "background-color:#FFB5C5" });
@Html.DropDownList("dropdownlist5",
new List()
{
new SelectListItem { Text="item---------1"},
new SelectListItem { Text="item---------2"},
new SelectListItem { Text="item---------3",Selected=true}
},
"Hello,World~",new { style = "background-color:#7B68EE" });
}
运行:
对应生成的网页源码:
IndexIndex
item---------1
item---------2
item---------3
item---------1
item---------2
item---------3
Hello,World~
item---------1
item---------2
item---------3
将View代码对比一下网页源码,即可知id,name的属性值是由该方法首参数而来,其中下拉框中的项目值是由集合参数而来。
2)Html.DropDownList方法
该方法跟上面的差不多,只不过支持强类型,首参数变成了Func<>,参考上面的TextBoxFor用法。
关于其它的控件如:CheckBox,RadiuButton等用法和上面的基本类似,都可以参考以上用法。详见MSDN中HtmlHelper扩展方法:点击打开链接