第五章 表单和HTML辅助方法
内容:
- 表单辅助方法
- 表单元素辅助方法
- 链接辅助方法
- PartialView和 ChildAction方法
HTML辅助方法主要作用:
- 确保HTML页面链接中URL指向正确位置
- 表单元素拥有适用于model binding的合适名称和值
- 当model binding失败时,其他元素能够显示相应的提示信息
一般HTML辅助方法
表单
//通过计算action来生成表单和正确的提交地址
@using (Html.BeginForm("Search","Home", FormMethod.Get)){
<input type="text" name="q" />
<input type="submit" value="Search" />
}
相当于:
@{
var context = this.ViewContext.RequestContext;
var values = new RouteValueDictionary{
{"controller", "home"}, {"action", "index"}
};
var path = RouteTable.Routes.GetVirtualPath(context,values);
<form action="@path.VirtualPath" method="get">
...
</form>
}
或者
@{Html.BeginForm("Search", "Home", FormMethod.Get);}
...
<input ...>
@{Html.EndForm();}
HTML辅助方法生成内容的时候会自动进行HTML编码
自定义HTML属性
Html.BeginForm("Search", "Home", FormMethod.Get,
new { //辅助方法的 htmlAttribute参数传入一个匿名对象来转换成html attribute
target = "_blank", //最后会生成属性 targer="_blank"
@class="editForm", //设置class属性的时候要加上@,因为class本身是C#关键字
data_validatable=true}) //对于带 - 的属性,替换成下划线来写,之后会生成 data-validatable="true"
原理
视图中的Html属性是基类的 System.Web.Mvc.HtmlHelper<T>
,里面的大部分辅助方法都是扩展方法.
Textbox
@Html.TextBox // <input type="text" />
@Html.TextArea //<textarea>
@Html.Label //<label >
列表
@Html.DropDownList // <select >
@Html.ListBox //<select multiple="multiple" >
验证
ModelState.AddModelError("Title", "error message for title");
@Html.ValidationMessage("Title") //只显示Title相关错误
@Html.ValidationSummary() //根据 ModelState的结果类显示错误信息
读取ViewBag的内容
//Action中设置:
ViewBag.Price = 10;
return View();
//View中:
@Html.TextBox("Price") // <input id="Price" name="Price" type="text" value="10" />
//Action中:
ViewBag.Album = new Album {Price = 11};
return View();
//View中:
@Html.TextBox("Album.Price") //<input id="Album_Price" name="Album.Price" type="text" value="11"/>
同理,如果数据在 Model中,也同样能够获取。
var album = new Album {Price = 12};
return View(album);
@Html.TextBox("Price"); // <input id="Price" name="Price" type="text" value = "12" />
强类型辅助方法
@model Album
@Html.LabelFor( model => model.GenreId)
@Html.DropDownListFor( model => model.GenreId, ViewBag.Genres as SelectList)
@Html.TextBoxFor(m => m.Title)
@Html.ValidationMessageFor(m=>m.Title)
方法名后面加了for,生成的html会使用C#属性名来当 name和id的值,并且根据对应C#属性的值,来替换标签的value
读取属性注解元数据
//定义属性注解
[DisplayName("Genre")]
public int GenreId {get;set;}
//View中
@Html.Label("GenreId") // <label for="GenereId">Genre</label>
//下面4个都是会根据注解信息来在运行时决定生成什么代码
@Html.Display
@Html.DisplayFor
@Html.Editor
@Html.EditorFor
//比如:
[DataType(DataType.MultilineText)]
public string Title{get;set;}
@Html.EditorFor( m => m.Title) // <textarea id= "Title" name="Title">
其他Html辅助方法
//<input type="hidden">
@Html.Hidden
@Html.HiddenFor
//<input type="password">
@Html.Password
@Html.PasswordFor
//<input type="radio">
@Html.RadioButton
@Html.RadioButtonFor
示例:
@Html.RadioButton("color","red") //<input id="color" name="color" type="radio" value="red"/>
@Html.RadioButton("color","blue", true) //<input id="color" name="color" type="radio" value="blue" checked="checked"/>
//渲染2个input
@Html.CheckBox("IsDiscounted")
//<input id="IsDiscounted" name="IsDiscounted" type="checkbox" value="true" />
//<input name="IsDiscounted" type="hidden" value="false" />
渲染辅助方法
Html链接
@Html.ActionLink // @Html.ActionLink("Link Text","Action", "Controller",para, htmlAttribute)
@Html.RouteLink //@Html.RouteLink("Link Text", new {action="Index"})
//区别是后者接收路由名称,而不是分别用字符串指定controller和action
Url辅助方法
和Html.ActionLink与RouteLink相似,但不是生成Html,而是返回字符串
@Url.Action
//@Url.Action("Browse","Store", new {genere="Jazz"}, null) --> /Store/Browse?genre=Jazz
@Url.Content
//相对路径转换成绝对路径 @Url.Content("~/Scripts/jquery.js")
@Url.RouteUrl
PartialView
@Html.Partial("ViewName") //将Partial视图解析成字符串写在这,使用更方便
@{ Html.RenderPatial("ViewName");} //直接将Partial视图写入响应输出流,性能更好
子Action
@Html.Action
@Html.RenderAction
[ChildActionOnly]
public ActionResult Menu(){
...
return PartialView();
}
//View中
@Html.Action("Menu")