我在文本框中有一个逗号分隔的字符串,我想将此字符串作为字符串数组传递给action方法。谁能告诉我怎样才能实现这一目标。感谢。
我正在使用MVC 1.0。
查看:
<input type="text" name="fruits" /> -- Contains the comma seperated values
行动方法
public ActionResult Index(string[] fruits)
{
}
答案 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
}