Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# MVC中的模型绑定字符串字段_C#_Asp.net Mvc 3_Model Binding - Fatal编程技术网

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

C# MVC中的模型绑定字符串字段,c#,asp.net-mvc-3,model-binding,C#,Asp.net Mvc 3,Model Binding,好的,我在MVC中遇到了一个问题,我将控制器/视图连接到多个模型,这些模型包含受保护的字符串内部集。创建这些对象时,我需要能够设置字符串。尽管如此,我在理解ModelBinding以完成此任务时遇到了问题。我为ModelBinder附加了一个非常基本的设置,但不知道从这里可以走到哪里: /// <summary> /// Handles binding for the string variables /// </summary> public class ActionR

好的,我在MVC中遇到了一个问题,我将控制器/视图连接到多个模型,这些模型包含受保护的字符串内部集。创建这些对象时,我需要能够设置字符串。尽管如此,我在理解ModelBinding以完成此任务时遇到了问题。我为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
}
好的,让我解释一下

您希望绑定一个模型,因此首先需要在

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.
}
工作完成了,如果你对此有更多问题,请告诉我

您真正不需要的更多信息:

允许您使用默认绑定行为并重写某些属性,就像您只使用字符串一样,但为此,您需要使用原始的bindModel方法。例如base.bindModel

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