MVC3 小记
<1> [Required] //必填项,
<2> [DataType] //字段属性, 如: DataType.Password , DataType.EmailAddress
<3> [Display(name="DisplayName")] //显示名称
<4> [StringLength] //设置字段长度大小
<5> [Remote("CheckIsExists","Account",AdditionalFields="FieldsName",ErrorMessage="")] //验证属性方法,
<6> [Compare("FieldName",ErrorMessage="")] //比较相等
<7> [RegularExpression(@"正则表达式",ErrorMessage="")] //正则验证
Views
使Views的page与Model对应, 在页头需要声明Model, 如: @model MvcApplication.Models.LogOnModel
一个与Model对应标准From的写法:
@using (Html.BeginForm()) {
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.Password)
@Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)
</div>
<p>
<input type="submit" value="Log On" />
</p>
</fieldset>
</div>
}
Controllers的写法是: 文件名 + Controller, 如Views下有个Account, 那么对应的Controllers就一定有个AccountController类,
Action对应Controller里的一个方法, 如: LogOn.cshtml对应 LogOn().
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
2) MVC3通过Global.asax中的RegisterRoutes() 来实现跳转到具体执行的类中, 如:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
3) 记录一点Model里远程验证[Remote()]的使用.
新建一个测试Model: TestModel, 如:
public class TestModel
{
[Required]
[Display(Name="First Name")]
[StringLength(10,MinimumLength=2,ErrorMessage="{0} is invalid,maxlength = {1} and minlength = {2}")]
public string FirstName { get; set; }
[Required]
[Display(Name="Last Name")]
[StringLength(10, MinimumLength = 2, ErrorMessage = "{0} is invalid , max length = {1} the minlength = {2}")]
[Remote("CheckIsExists", "Account", AdditionalFields = "FirstName", ErrorMessage = "{0} was exists,please change to other one.")]
public string LastName { get; set; }
}
TestRemote.cshtml页面如下:
@model MvcApplication.Models.TestModel
@{
ViewBag.Title = "TestRemote";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<h2>
Test the Remote</h2>
@Html.ValidationSummary(true, "the value of username is invalid, please middfied and try agin later.")
@using (Html.BeginForm())
{
<div id="div">
<fieldset>
<div class="editor-label">
@Html.LabelFor(m => m.FirstName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m => m.FirstName)
@Html.ValidationMessageFor(m=>m.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(m=>m.LastName)
</div>
<div class="editor-field">
@Html.TextBoxFor(m=>m.LastName)
@Html.ValidationMessageFor(m=>m.LastName)
@Html.HiddenFor(m => m.FirstName)
</div>
<p>
<input type="submit" value="Valid" />
</p>
</fieldset>
</div>
}
注: 由于远程验证用到Jquery的验证方法, 因此 jquery.validate.min.js 和 jquery.validate.unobtrusive.min.js 文件引用不可少.
Controller中的Action, CheckIsExists()如下:
[HttpGet]
public ActionResult CheckIsExists(Models.TestModel model)
{
bool exists = model.FirstName == "ppp" && model.LastName=="ppp" ? true : false;
return Json(!exists, JsonRequestBehavior.AllowGet);
}
注: Romote中的AdditionalFields 可以声明多个Fields, 以逗号隔开. 但是在前台必须对应声明一个@Html.HiddenFor(...).