MVC 中的模型绑定字符串字段

本文关键字:字符串 字段 绑定 模型 MVC | 更新日期: 2023-09-27 18:35:11

好的,我在MVC中遇到了问题,其中我有控制器/视图附加到多个模型,这些模型包含字符串的受保护内部集。创建这些对象时,我需要能够设置字符串。话虽如此,我在理解模型绑定以实现此目的时遇到了问题。我已经为ModelBinder附加了一个非常基本的设置,但不知道从这里开始:

/// <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
}

MVC 中的模型绑定字符串字段

好的,

让我解释一下。

你想要绑定一个模型,所以首先你需要在

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"]

但是你可以从QueryString或任何你想要的东西中获取值,因为你在这里有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 方法。(例如基地。绑定模型)