You can create a custom model binder to achieve this. Create a class like this to do the split.
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
}
Then you can instruct the framework to use this model binder with your action like this.
public ActionResult Index([ModelBinder(typeof(StringSplitModelBinder))] string[] fruits)
{
}
Instead of applying the ModelBinder
attribute to action method parameters you can also register the custom model binder globally in the application start method of your Global.asax.
ModelBinders.Binders.Add(typeof(string[]), new StringSplitModelBinder());
This will split the single string value posted to the array you require.
Please note that the above was created and tested using MVC 3 but should also work on MVC 1.0.