1 <div> 2 @using(Html.BeginForm("Test","Default")) 3 { 4 @Html.TextBox("name","rupeng");
@Html.Label("UserName","用户名:")@Html.TextBox("UserName") 5 } 6 </div>
自定义属性:
1、定义一个Model:Person类
1 class Person 2 { 3 public int Age{get;set;}
public int Height{get;set; 4 }
<div> @using(Html.BeginForm("Test","Default")) { Person p1 = new Person(){Age=66,Height=166} @Html.TextBox("name","rupeng",p1);//生成的HTML代码中就会添加上Age属性和Height属性 } </div>
或者经常用匿名类
1 <div> 2 @using(Html.BeginForm("Test","Default")) 3 { 4 var p1 = new {haha=66,xixi=166} 5 @Html.TextBox("name","rupeng",p1);//生成的HTML代码中就会添加上haha属性和xixi属性 6 } 7 </div>
实际应用:
定义一个class类属性
<style type="text/css"> .warn{ color:red; } </style>
<div> @using(Html.BeginForm("Test","Default")) { @Html.TextBox("name","rupeng",new {@class="warn",data_val="haha"});//生成的HTML代码中就会添加上class属性(值为warn)和data-val属性 } </div>
用于表单验证:
有一个Model,Person类
1 public class Person 2 { 3 [DisplayName("用户名")] 4 [Required] 5 [StringLength(8)] 6 public string UserName { get; set; } 7 8 [DisplayName("密码")] 9 [Required] 10 [StringLength(8)] 11 public string Password { get; set; } }
cshtml中代码
1 @using (Html.BeginForm("Login","Default")) { <span>用户名:</span>@Html.TextBox("UserName") <span>密码:</span>@Html.Password("Password") <input type="submit" value="提交"/> @Html.ValidationSummary() }
注:如果字段比较多,汇总消息显然不合适,那么就用@Html.ValidationMessage("UserName")值只显示UserName属性相关的错误信息。
比如:
1 @using (Html.BeginForm("Login","Default")) { <span>用户名:</span>@Html.TextBox("UserName") <span> @Html.ValidationMessage("UserName")</br> 2 密码:</span>@Html.Password("Password") <input type="submit" value="提交"/> }
controller中代码
1 public ActionResult Index() { return View(); } 2 public ActionResult Login(Person model) 3 { 4 if(!ModelState.IsValid) 5 { 6 return View("Index");//一定要返回表单原始页面 7 } 8 return Content(model.UserName); 9 }