한 가지 가능한 방법으로 접근하는 몇 가지 방법을의 사용자 정의 모델 바인더 때문이다.
public class Customer
{
public string Name { get; set; }
public DateTime Date { get; set; }
}
public class PageController : Controller
{
[HttpPost]
public ActionResult ActionA(Customer customer)
{
if(ModelState.IsValid) {
//do something with the customer
}
}
[HttpPost]
public ActionResult ActionB(Customer customer)
{
if(ModelState.IsValid) {
//do something with the customer
}
}
}
CustomerModelBinder는 그런 일이 될 것입니다 :
public class CustomerModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "Name") //or date or whatever else you want
{
//Access your Name property with valueprovider and do some magic before you bind it to the model.
//To add validation errors do (simple stuff)
if(string.IsNullOrEmpty(bindingContext.ValueProvider.GetValue("Name").AttemptedValue))
bindingContext.ModelState.AddModelError("Name", "Please enter a valid name");
//Any complex validation
}
else
{
//call the usual binder otherwise. I noticed that in this way you can use DataAnnotations as well.
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
을하고 Global.asax에 넣어에서 여기 내가 POST-폼 데이터에 사용자 지정 유효성 검사를 추가하기 위해 최근에 사용 무엇의 작은 샘플입니다
ModelBinders.Binders.Add(typeof(Customer), new CustomerModelBinder());
당신이 이름 속성 (단지 일) 당신이 ActionB를 호출 할 때, 다음 하나 이상의 사용자 정의 모델 바인더와의 명령문 "만일", 넣어 다시 할 수 있도록 바인딩하지하려면 널 (null) 또는 이미 존재하는 값이나 원하는 값을 설정하십시오. 그런 다음 컨트롤러 넣어에서 :
[HttpPost]
public ActionResult([ModelBinder(typeof(CustomerAModelBinder))] Customer customer)
[HttpPost]
public ActionResult([ModelBinder(typeof(CustomerBModelBinder))] Customer customer)
customerAmodelbinder에만 이름을 바인딩하고 customerBmodelbinder는 날짜를 결합 할 경우.
이것은 모델 바인딩의 유효성을 검사하는 가장 쉬운 방법이며 복잡한보기 모델을 사용하여 매우 멋진 결과를 얻었습니다. 내가 놓친 뭔가가있을 것이고 아마도 전문가가 대답 할 수있을 것입니다. 희망 사항을 바로 잡았습니다. :)
Employee {string Name {get; 세트; } 날짜 시간? 날짜 {get; 세트; }}, Action A의 Employee 인스턴스에는 무엇이 포함됩니까? 당신은 그것이 오직 이름을 묶어야한다고 말했다. 날짜가 널일까요? 더 나은 그림을 얻으려고. –
@Raje : nope. Employee 객체가 영구 저장소에 저장되기 전에 몇 가지 추가 논리가 적용됩니다 (이 문제를 해결하기 위해 몇 초 안에 질문을 업데이트 중입니다) – zerkms
http://bradwilson.typepad.com/ 이미이 뛰어난 기사를 읽은 적이 있는지 확실하지 않습니다. 블로그/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html –