ASP.NET MVC Preview 5에서 새로운 ModelBinder 클래스를 어떻게 사용합니까?

StackOverflow https://stackoverflow.com/questions/34709

  •  09-06-2019
  •  | 
  •  

문제

Preview 5의 릴리스 정보에는 다음이 포함되어 있습니다.

사용자 정의 모델 바인더에 대한 지원이 추가되었습니다.사용자 정의 바인더를 사용하면 복합 유형을 작업 메서드에 대한 매개 변수로 정의할 수 있습니다.이 기능을 사용하려면 복합 유형 또는 매개변수 선언을 [ModelBinder(…)]로 표시하십시오.

그렇다면 내 컨트롤러에서 다음과 같은 작업을 수행할 수 있도록 이 기능을 실제로 사용하는 방법은 무엇입니까?

public ActionResult Insert(Contact contact)
{
    if (this.ViewData.ModelState.IsValid)
    {
        this.contactService.SaveContact(contact);

        return this.RedirectToAction("Details", new { id = contact.ID}
    }
}

다른 팁

글쎄, 나는 이것을 조사했다.ASP.NET은 IControlBinder 구현을 등록하기 위한 공통 위치를 제공합니다.또한 새로운 Controller.UpdateModel 메서드를 통해 작업하는 기본 사항도 있습니다.

그래서 저는 modelClass의 모든 공용 속성에 대해 Controller.UpdateModel과 동일한 작업을 수행하는 IModelBinder 구현을 만들어 기본적으로 이 두 가지 개념을 결합했습니다.

public class ModelBinder : IModelBinder 
{
    public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)
    {
        object model = Activator.CreateInstance(modelType);

        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(model);
        foreach (PropertyDescriptor descriptor in properties)
        {
            string key = modelName + "." + descriptor.Name;
            object value = ModelBinders.GetBinder(descriptor.PropertyType).GetValue(controllerContext, key, descriptor.PropertyType, modelState);
            if (value != null)
            {
                try
                {
                    descriptor.SetValue(model, value);
                    continue;
                }
                catch
                {
                    string errorMessage = String.Format("The value '{0}' is invalid for property '{1}'.", value, key);
                    string attemptedValue = Convert.ToString(value);
                    modelState.AddModelError(key, attemptedValue, errorMessage);
                }
            }
        }

        return model;
    }
}

Global.asax.cs에 다음과 같은 내용을 추가해야 합니다.

    protected void Application_Start()
    {
        ModelBinders.Binders.Add(typeof(Contact), new ModelBinder());
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top