
下拉框和多选列表框
-
expression:表达式名称,一般用于表示文本框的name。
-
selectList:下拉列表的数据源,IEnumerable<SelectListItem>类型,一般用SelectList实现。
-
optionLabel:默认显示的文本
-
htmlAttributes:超链接Html属性,如:style,class,width,height等,可以接收匿名对象。
List<City> cityList = new List<City>{new City() { Id = 1, Name = "北京" },new City() { Id = 2, Name = "上海" },new City() { Id = 3, Name = "广州" },new City() { Id = 4, Name = "深圳" }};var citys = new SelectList(cityList, "Id", "Name");ViewBag.Citys = citys;
@Html.Label("City","城市",new { style="width:90px;"})@Html.DropDownList("City", ViewBag.Citys,"请选择",new {style="width:120px;"})
-
expression:表达式名称,一般用于表示文本框的name。
-
selectList:下拉列表的数据源,IEnumerable<SelectListItem>类型,一般用SelectList实现。
-
htmlAttributes:超链接Html属性,如:style,class,width,height等,可以接收匿名对象。
@Html.Label("MultiCity","多选城市",new { style="width:90px;vertical-align:top;"})@Html.ListBox("MultiCity", ViewBag.Citys,new {style="width:120px;"})
<label for="City" style="width:90px;">城市</label><select id="City" name="City" style="width:120px;"><option value="">请选择</option><option value="1">北京</option><option value="2">上海</option><option value="3">广州</option><option value="4">深圳</option></select><br><br><label for="MultiCity" style="width:90px;vertical-align:top;">多选城市</label><select id="MultiCity" multiple="multiple" name="MultiCity" style="width:120px;"><option value="1">北京</option><option value="2">上海</option><option value="3">广州</option><option value="4">深圳</option></select>
Html转义
-
value:需要是输出的内容,有string和TModel两种类型。
@Html.Raw("<font color='red'>大家好,这是测试Raw输出</font>")模型校验
-
-
[CreditCard]:验证属性是否具有信用卡格式。 -
[Compare]:验证某个模型中的两个属性是否匹配。 -
[EmailAddress]:验证属性是否具有电子邮件格式。 -
[Phone]:验证属性是否具有电话格式。 -
[Range]:验证属性值是否落在给定范围内。 -
[RegularExpression]:验证数据是否与指定的正则表达式匹配。 -
[Required]:将属性设置为必需属性。 -
[StringLength]:验证字符串属性是否最多具有给定的最大长度。 -
[Url]:验证属性是否具有 URL 格式。
-
模型校验步骤
using System.ComponentModel.DataAnnotations;namespace DemoCoreMVC.Models{public class User{[Required(ErrorMessage ="Id不能为空")][Range(0, 100,ErrorMessage ="Id必须从0到100之内")]public int Id { get; set; }[Required(ErrorMessage ="用户名称不能为空")]public string Name { get; set; }[Required(ErrorMessage ="邮箱不可为空")][EmailAddress(ErrorMessage ="邮件不符合格式")]public string Email { get; set; }}}
<!--Edit.cshtml文件的底部增加以下引入部分视图-->@section Scripts{@(await Html.PartialAsync("_ValidationScriptsPartial"))}
@using (Html.BeginForm("Save","User",FormMethod.Post)){@Html.Label("Id","User Id",new { style="width:90px;"});@Html.TextBox("Id",Model.Id)@Html.ValidationMessageFor(p=>p.Id)<br /><br />@Html.Label("Name","User Name",new { style="width:90px;"})@Html.TextBox("Name",Model.Name)@Html.ValidationMessageFor(p=>p.Name)<br /><br />@Html.Label("Email","E-Mail",new { style="width:90px;"})@Html.TextBox("Email",Model.Email)@Html.ValidationMessageFor(p=>p.Email)<br /><br /><input type="submit" value="保存" class="btn btn-primary" />}
