1

사용자 지정 문자열 개체를 만들었지 만 서버에 게시 할 때 모델 바인딩하지 않습니다. 수업에 실종 된 속성이 있습니까? MVC에서 사용자 정의 문자열 객체 모델을 만드는 방법은 무엇입니까?

아래의 사용자 정의 문자열 클래스입니다 :

위해
public class EMailAddress 
{ 
    private string _address; 
    public EMailAddress(string address) 
    { 
     _address = address; 
    } 
    public static implicit operator EMailAddress(string address) 
    { 
     if (address == null) 
      return null; 
     return new EMailAddress(address); 
    } 
} 

답변

1

가 기본 매개 변수가없는 생성자가 있어야 바인더 객체가 올바르게 기본 모델에 구속되기 위해서는 다음과 같은 경우

public class EMailAddress 
{ 
    public string Address { get; set; } 
} 

을 보여준 모델로 모델을 사용하려면 변환을 처리 할 사용자 정의 모델 바인더를 작성해야합니다.

public class EmailModelBinder : DefaultModelBinder 
{ 
    public override object BindModel(
     ControllerContext controllerContext, 
     ModelBindingContext bindingContext 
    ) 
    { 
     var email = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); 
     if (email != null) 
     { 
      return new EMailAddress(email.AttemptedValue); 
     } 
     return new EMailAddress(string.Empty); 
    } 
} 
Application_Start에 등록됩니다

:

ModelBinders.Binders.Add(typeof(EMailAddress), new EmailModelBinder()); 

과 같이 사용 :

public class HomeController : Controller 
{ 
    public ActionResult Index(EMailAddress email) 
    { 
     return View(); 
    } 
} 

이제 작업 매개 변수를 적절하게 결합되어야한다 /Home/[email protected] 쿼리 할 때.

이제 질문은 : 내가 처음에 보여준 것과 같이 뷰 모델을 가질 수있을 때이 코드를 모두 작성 하시겠습니까?

+0

네, 이것은 내가 대린을 찾고있는 것입니다! 고맙습니다! :) –

관련 문제