ASP.NET MVC #13
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۱/۲۲ ۲۲:۳۵:۰۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication9.Models
{
public class Customer
{
public int Id { set; get; }
[Required(ErrorMessage = "Name is required.")]
[StringLength(50)]
public string Name { set; get; }
[Display(Name = "Email address")]
[Required(ErrorMessage = "Email address is required.")]
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
ErrorMessage = "Please enter a valid email address.")]
public string Email { set; get; }
[Range(0, 10)]
[Required(ErrorMessage = "Rating is required.")]
public double Rating { set; get; }
[Display(Name = "Start date")]
[Required(ErrorMessage = "Start date is required.")]
public DateTime StartDate { set; get; }
}
}
using System.Web.Mvc;
using MvcApplication9.Models;
namespace MvcApplication9.Controllers
{
public class CustomerController : Controller
{
[HttpGet]
public ActionResult Create()
{
var customer = new Customer();
return View(customer);
}
[HttpPost]
public ActionResult Create(Customer customer)
{
if (this.ModelState.IsValid)
{
//todo: save data
return Redirect("/");
}
return View(customer);
}
}
}
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
@{ Html.EnableClientValidation(false); }
<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>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Customer</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<input data-val="true" data-val-required="The Birthday field is required." id="Birthday" name="Birthday" type="text" value="" />
<script src="../../Scripts/customvaildation.js" type="text/javascript"></script>
using System;
using System.ComponentModel.DataAnnotations;
namespace MvcApplication9.CustomValidators
{
public class MyDateValidator : ValidationAttribute
{
public int MinYear { set; get; }
public override bool IsValid(object value)
{
if (value == null) return false;
var date = (DateTime)value;
if (date > DateTime.Now || date < new DateTime(MinYear, 1, 1))
return false;
return true;
}
}
}
[Display(Name = "Start date")]
[Required(ErrorMessage = "Start date is required.")]
[MyDateValidator(MinYear = 2000,
ErrorMessage = "Please enter a valid date.")]
public DateTime StartDate { set; get; }
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MvcApplication9.CustomValidators;
namespace MvcApplication9.Models
{
public class Customer : IValidatableObject
{
//... same as before
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var fields = new[] { "StartDate" };
if (StartDate > DateTime.Now || StartDate < new DateTime(2000, 1, 1))
yield return new ValidationResult("Please enter a valid date.", fields);
if (Rating > 4 && StartDate < new DateTime(2003, 1, 1))
yield return new ValidationResult("Accepted date should be greater than 2003", fields);
}
}
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var info = validationContext.ObjectType.GetProperty("Rating");
//...
return ValidationResult.Success;
}
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Collections.Generic;
namespace MvcApplication9.CustomValidators
{
public class MyDateValidator : ValidationAttribute, IClientValidatable
{
// ... same as before
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata,
ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ValidationType = "mydatevalidator",
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName())
};
yield return rule;
}
}
}
/// <reference path="jquery-1.5.1-vsdoc.js" />
/// <reference path="jquery.validate-vsdoc.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
jQuery.validator.addMethod("mydatevalidator",
function (value, element, param) {
return Date.parse(value) < new Date();
});
jQuery.validator.unobtrusive.adapters.addBool("mydatevalidator");
<script src="@Url.Content("~/Scripts/customvaildation.js")" type="text/javascript"></script>
1. .field-validation-error
2. .field-validation-valid
3. .input-validation-error
4. .input-validation-valid
5. .validation-summary-errors
6. .validation-summary-valid
[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
class CustomerMetadata
{
}
}
public partial class Customer : IValidatableObject
{
[Required(ErrorMessage = "Name is required.")]
[StringLength(50)]
[System.Web.Mvc.Remote(action: "CheckUserNameAndEmail",
controller: "Customer",
AdditionalFields = "Email",
HttpMethod = "POST",
ErrorMessage = "Username is not available.")]
public string Name { set; get; }
[HttpPost]
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public ActionResult CheckUserNameAndEmail(string name, string email)
{
if (name.ToLowerInvariant() == "vahid") return Json(false);
if (email.ToLowerInvariant() == "name@site.com") return Json(false);
//...
return Json(true);
}
using System.ComponentModel.DataAnnotations;
namespace MvcApplication9.Helper
{
public static class ValidationHelper
{
public static bool TryValidateObject(this object instance)
{
return Validator.TryValidateObject(instance, new ValidationContext(instance, null, null), null);
}
}
}
"^\\d{4}/\\d{2}/\\d{2}$"
public class CustomProfile
{
[Required(ErrorMessage="*")]
[StringLength(50)]
[System.Web.Mvc.Remote(action: "CheckUserName",
controller: "User",
HttpMethod = "POST",
ErrorMessage = "این نام کاربری وجود دارد")]
public string Username{ get; set; }
[Required(ErrorMessage = "*")]
public string Password{ get; set; }
[Required(ErrorMessage = "*")]
public string FirstName{ get; set; }
[Required(ErrorMessage = "*")]
public string LastName{ get; set; }
[Required(ErrorMessage = "*")]
[StringLength(10, ErrorMessage = "کدملی باید 10 رقم باشد")]
public string NationalCode { get; set; }
[Required(ErrorMessage = "*")]
public string Address { get; set; }
[RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",
ErrorMessage = "آدرس ایمیل معتبر نیست")]
[System.Web.Mvc.Remote(action: "CheckEmail",
controller: "User",
AdditionalFields = "Username",
HttpMethod = "POST",
ErrorMessage = "این ایمیل وجود دارد")]
public string Email{ get; set; }
[StringLength(11, ErrorMessage = "تلفن باید 11 رقم باشد")]
public string PhoneNo{ get; set; }
[StringLength(11, ErrorMessage = "موبایل باید 11 رقم باشد")]
public string MobileNo{ get; set; }
public string[] Roles{ get; set; }
public string LastActivityDate{ get; set; }
public string LastLoginDate { get; set; }
public string CreationDate { get; set; }
public bool IsLockedOut{ get; set; }
}
@model Sama.Models.CustomProfile
@{
ViewBag.Title = "Create";
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>
@using (Html.BeginForm(actionName: "Create", controllerName: "User"))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>کاربر جدید</legend>
<div>
<table>
<tr>
<td>
<div>
@Html.LabelFor(model => model.Username, "نام کاربری")
</div>
</td>
<td>
<div>
@Html.EditorFor(model => model.Username)
@Html.ValidationMessageFor(model => model.Username)
</div>
</td>
</tr>
<tr>
<td>
<div>
@Html.LabelFor(model => model.Password, "کلمه عبور")
</div>
</td>
<td>
<div>
@Html.PasswordFor(model => model.Password)
@Html.ValidationMessageFor(model => model.Password)
</div>
</td>
</tr>
<tr>
<td>
<div>
@Html.LabelFor(model => model.FirstName, "نام")
</div>
</td>
<td>
<div>
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</td>
</tr>
<tr>
<td>
<div>
@Html.LabelFor(model => model.LastName, "نام خانوادگی")
</div>
</td>
<td>
<div>
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
</td>
</tr>
<tr>
<td>
<div>
@Html.LabelFor(model => model.NationalCode, "کد ملی")
</div>
</td>
<td>
<div>
@Html.EditorFor(model => model.NationalCode)
@Html.ValidationMessageFor(model => model.NationalCode)
</div>
</td>
</tr>
<tr>
<td>
<div>
@Html.LabelFor(model => model.Email, "ایمیل")
</div>
</td>
<td>
<div>
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
</td>
</tr>
<tr>
<td>
<div>
@Html.LabelFor(model => model.PhoneNo, "تلفن")
</div>
</td>
<td>
<div>
@Html.EditorFor(model => model.PhoneNo)
@Html.ValidationMessageFor(model => model.PhoneNo)
</div>
</td>
</tr>
<tr>
<td>
<div>
@Html.LabelFor(model => model.MobileNo, "موبایل")
</div>
</td>
<td>
<div>
@Html.EditorFor(model => model.MobileNo)
@Html.ValidationMessageFor(model => model.MobileNo)
</div>
</td>
</tr>
<tr>
<td>
<div>
@Html.LabelFor(model => model.Address, "آدرس")
</div>
</td>
<td>
<div>
@Html.TextAreaFor(model => model.Address, 5, 30, null)
@Html.ValidationMessageFor(model => model.Address)
</div>
</td>
</tr>
<tr>
<td>
نقشها </td>
<td>
@Helper.CheckBoxList("Roles", (List<SelectListItem>)ViewBag.Roles)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" value="ذخیره" class="btn btn-primary" />
</td>
</tr>
</table>
</div>
</fieldset>
}
[MetadataType(typeof(Customer_Validation))]
public partial class Customer
{
}
public class Customer_Validation
{
}
@model Models.Account
@{
Layout = null;
ViewBag.Title = "ورود به سیستم";
}
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<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>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Login</legend>
<table style="font-size: 8pt">
<tr>
<td style="width: 100px; text-align: left">نام کاربری :</td>
<td>@Html.EditorFor(model => model.Username)</td>
</tr>
<tr>
<td></td>
<td style="color: red">@Html.ValidationMessageFor(model => model.Username)</td>
</tr>
<tr>
<td style="width: 100px; text-align: left">کلمه عبور :</td>
<td>@Html.EditorFor(model => model.Password)</td>
</tr>
<tr>
<td></td>
<td style="color: red">@Html.ValidationMessageFor(model => model.Password)</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="ورود به سیستم" /></td>
</tr>
</table>
</fieldset>
}
public class Account
{
[Required(ErrorMessage = "نام کاربری باید وارد شود.")]
[StringLength(20)]
public string Username { get; set; }
[Required(ErrorMessage = "کلمه عبور باید وارد شود.")]
[DataType(DataType.Password)]
public string Password { get; set; }
}
[HttpGet]
public ActionResult LogOn(string returnUrl)
{
if (User.Identity.IsAuthenticated) //remember me
{
if (shouldRedirect(returnUrl))
{
return Redirect(returnUrl);
}
return Redirect(FormsAuthentication.DefaultUrl);
}
return View(); // show the login page
}
[HttpPost]
public ActionResult LogOn(Account loginInfo, string returnUrl)
{
if (this.ModelState.IsValid)
{
List<User> users = _userService.GetUser(loginInfo.Username, loginInfo.Password);
if (users != null && users.Count == 1)
{
FormsAuthentication.SetAuthCookie(loginInfo.Username,false);// loginInfo.RememberMe);
//-- کاربر برنامه ریزی
if (users.First().UserType_Id == 1)
{
return RedirectToAction("Index", "Programming", new { u = loginInfo.Username });
}
else if (users.First().UserType_Id == 2)
{
}
else if (users.First().UserType_Id == 3)
{
}
else if (users.First().UserType_Id == 4)
{
}
}
}
this.ModelState.AddModelError("", "نام کاربری یا کلمه عبور اشتباه وارد شده اند.");
ViewBag.Error = "";
return View(loginInfo);
}
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
http://localhost:2215/Account/LogOn?ReturnUrl=%2fScripts%2fjquery-1.7.1.js
<authorization>
<deny users="?" />
</authorization>
routes.IgnoreRoute("Content/{*pathInfo}");
routes.IgnoreRoute("Scripts/{*pathInfo}");
return Date.parse(value) < new Date();
jQuery.validator.addMethod("mydatevalidator",
function (value, element, param) {
mcvrTwo.ValidationParameters.Add("param", DateTime.Now.ToString("dd/MM/yyyy"));mcvrTwo.ValidationParameters.Add("param", DateTime.Now.ToString("dd-MM-yyyy"));@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}The type name 'ModelClientValidationRule' could not be found. This type has been forwarded to assembly 'System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. Consider adding a reference to that assembly.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
public class MyViewModel
{
[Required]
public string CategoryId { get; set; }
public IEnumerable<Category> Categories { get; set; }
}
Controller:
public ActionResult Index()
{
var model = new MyViewModel
{
Categories = GetCategories()
}
return View(model);
}
View:
@Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.Categories, "ID", "CategoryName"),
"-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId) [System.Web.Mvc.Remote(action: "CheckUserNameAndEmail",
controller: "Customer",
AdditionalFields = "Email",
HttpMethod = "POST",
ErrorMessage = "Username is not available.")] DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredAttribute), typeof(CustomRequiredAttributeAdapter)); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(StringLengthAttribute), typeof(CustomStringLengthAttributeAdapter)); DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RangeAttribute), typeof(CustomRangeAttributeAdapter));