使用模型获取绑定数据:
[RegularExpression]约束邮箱规范使用.
多行文本框;
<p>评论:@Html.TextArea("desc",null,5,30,null)</p>
Person类;
public class Person
{
public string ID { get; set; }
public string Name { get; set; }
public string Num { get; set; }
}
<body>
<h1>个人信息</h1>
@using (Html.BeginForm())
{
<table>
<tr>
<th>ID</th>
<td>@Html.TextBox("id")</td>
</tr>
<tr>
<th>Name</th>
<td>@Html.TextBox("name")</td>
</tr>
<tr>
<th>Num</th>
<td>@Html.TextBox("num")</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="name" value="提交" />
</td>
</tr>
<tr>
<td colspan="2">
<strong>
@ViewBag.msg
</strong>
</td>
</tr>
</table>
}
</body>
[HttpPost]
//Person是文件里新建的一个类。
public ActionResult Index(Person p)
{
ViewBag.msg = "商品编号是: " + p.ID + " 商品名称是: " + p.Name + " 商品数量是: " + p.Num;
return View();
}
运行结果:
模型验证:
public class Movie
{
[DisplayName("影片名称")]
[Required(ErrorMessage = "{0}不能为空")]
public string Name { get; set; }
[DisplayName("上映日期")]
[DataType(DataType.Date, ErrorMessage = "{0}的日期格式不对")]
public DateTime ReleaseDate { get; set; }
[DisplayName("光盘价格")]
[Range(1, 100, ErrorMessage = "{0}必须在1-100之间")]
public decimal Price { get; set; }
[DisplayName("评分")]
[StringLength(10, ErrorMessage = "{0}必须在10个字以内")]
public string Rating { get; set; }
[RegularExpression("^\\s*([A-Za-z0-9_-]+(\\.\\w+)*@(\\w+\\.)+\\w{2,5})\\s*$", ErrorMessage ="{0}邮箱格式不正确")]
public string userEmail { get; set; }
}
前端增加一条代码: @Html.ValidationSummary()。
<tr>
<td></td>
<td>
<input type="submit" value="新增影片" />
@Html.ValidationSummary()
@ViewBag.Info
</td>