Asp.net MVC - 在动作方法中将逗号分隔的字符串分隔为字符串数组

时间:2011-08-08 10:48:08

标签: asp.net-mvc

我在文本框中有一个逗号分隔的字符串,我想将此字符串作为字符串数组传递给action方法。谁能告诉我怎样才能实现这一目标。感谢。

我正在使用MVC 1.0。

查看:

<input type="text" name="fruits" /> -- Contains the comma seperated values

行动方法

public ActionResult Index(string[] fruits)
{

}

2 个答案:

答案 0 :(得分:7)

您可以创建自定义模型绑定器来实现此目的。创建一个这样的类来进行拆分。

public class StringSplitModelBinder : IModelBinder
{
    #region Implementation of IModelBinder

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (!bindingContext.ValueProvider.ContainsKey(bindingContext.ModelName))
        {
            return new string[] { };
        }

        string attemptedValue = bindingContext.ValueProvider[bindingContext.ModelName].AttemptedValue;
        return !String.IsNullOrEmpty(attemptedValue) ? attemptedValue.Split(',') : new string[] { };
    }

    #endregion
}

然后,您可以指示框架将此模型绑定器与您的操作一起使用。

public ActionResult Index([ModelBinder(typeof(StringSplitModelBinder))] string[] fruits)
{
}

您可以在Global.asax的应用程序启动方法中全局注册自定义模型绑定器,而不是将ModelBinder属性应用于操作方法参数。

ModelBinders.Binders.Add(typeof(string[]), new StringSplitModelBinder());

这会将发布到您需要的数组的单个字符串值拆分。

请注意,上面的内容是使用MVC 3创建和测试的,但也适用于MVC 1.0。

答案 1 :(得分:4)

将文本框的字符串(带逗号)直接传递给控制器​​操作,并在操作内部创建数组。

public ActionResult Index(string fruits)
{
    var fruitsArray = fruits.Split(',');
    // do something with fruitArray
}