开发者

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 an开发者_JAVA技巧yone 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)
{

}


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.


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜