2012-05-24 4 views
1

OK У меня проблема с MVC, где у меня есть контроллеры/представления, прикрепленные к нескольким моделям, которые содержат защищенные внутренние наборы для строк. Когда эти объекты создаются, мне нужно, чтобы строки могли быть установлены. Сказав, что у меня возникают проблемы с пониманием ModelBinding для достижения этого. Я приложил очень простой набор для ModelBinder, но не знаю, куда идти отсюда:Model Binding строковые поля в MVC

/// <summary> 
/// Handles binding for the string variables 
/// </summary> 
public class ActionResultModelBinder : DefaultModelBinder, IModelBinder, ITypedModelBinder 
{ 
    #region Properties 

    /// <summary> 
    /// Gets the type that this model binder's associated with 
    /// </summary> 
    /// <value> 
    /// The type that this model binder's associated with. 
    /// </value> 
    public Type AssociatedType 
    { 
     get 
     { 
      return typeof(string); 
     } 
    } 

    #endregion Properties 

    #region Methods 

    /// <summary> 
    /// Binds the model by using the specified controller context and binding context. 
    /// </summary> 
    /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param> 
    /// <param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param> 
    /// <returns> 
    /// The bound object. 
    /// </returns> 
    /// <exception cref="T:System.ArgumentNullException">The <paramref name="bindingContext "/>parameter is null.</exception> 
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     var boundValue = base.BindModel(controllerContext, bindingContext); 
     return bindingContext.ModelType == typeof(string); 
    } 

    /// <summary> 
    /// Sets the specified property by using the specified controller context, binding context, and property value. 
    /// </summary> 
    /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param> 
    /// <param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param> 
    /// <param name="propertyDescriptor">Describes a property to be set. The descriptor provides information such as the component type, property type, and property value. It also provides methods to get or set the property value.</param> 
    /// <param name="value">The value to set for the property.</param> 
    protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) 
    { 
     if (propertyDescriptor.PropertyType == typeof(string)) 
     { 
      var stringVal = value as string; 
     } 

     base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value); 
    } 

    #endregion Methods 
} 

ответ

0

Хорошо, позвольте мне объяснить.

Вы хотите связать модель поэтому сначала вам нужно вернуть эту модель в

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 

здесь пример заказных связующего для связывания модели под названием FacebookGroupViewModel:

public class FacebookGroupViewModelBinder : IModelBinder 
    { 
     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
     { 
      var model = new FacebookGroupViewModel(); 
      if(controllerContext.HttpContext.Request.Form.AllKeys.Contains("Friends")) 
      { 
       var friends = controllerContext.HttpContext.Request.Form["Friends"].Split(','); 
       foreach (var friend in friends) 
       { 
        model.FacebookFriendIds.Add(friend); 
       } 


} 
      return model; 
     } 
    } 

Здесь вы можете см., что я извлекаю значение из формы:

controllerContext.HttpContext.Request.Form["Friends"] 

, но вы можете получить значение из QuerySt кольцо или что угодно, поскольку у вас есть HttpContext здесь. Отлаживайте и смотрите на все имущество, которое вам нужно узнать больше.

Наконец, вам нужно настроить это связующее и связать его с вашей моделью в global.asax, выполнив этот путь.

ModelBinders.Binders.Add(typeof(FacebookGroupViewModel),new FacebookGroupViewModelBinder()); 

В способе запуска приложения.

Тогда просто используйте Представьте, что мой контроллер такой.

[HttpPost] 
public ActionResult PostFriend(FacebookGroupViewModel model) 
{ 
//here your model is binded by your custom model ready to use. 
} 

Работа выполнена, дайте мне знать, если у вас есть еще вопрос об этом.

Более подробная информация, что вы на самом деле не нужно:

protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) 

Позволяет использовать поведение связующего по умолчанию и переопределить некоторые свойства, как вы делали только строки, но для этого нужно использовать оригинал метод bindModel (например, base.BindModel)