Bhaskar
Bhaskar

Reputation: 1690

Asp.net MVC - Mapping comma separated string to string array in action method

I have a comma separated string in a textbox, I want to pass this string as string array to an action method. Could anyone tell me how can I achieve this. thanks.

I am using MVC 1.0.

Views:

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

Action method

public ActionResult Index(string[] fruits)
{

}

Upvotes: 2

Views: 8692

Answers (2)

gusztav.varga.dr
gusztav.varga.dr

Reputation: 476

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.

Upvotes: 6

Sandro
Sandro

Reputation: 3160

Pass the string (with the commas) of your textbox directly to the controller action and create the array inside of the action.

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

Upvotes: 7

Related Questions