Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC pass ids separated by "+" to action

I want to have possibility to access action by the following URL type:

http://localhost/MyControllerName/MyActionName/Id1+Id2+Id3+Id4 etc.

and handle it in code in the following way:

public ActionResult MyActionName(string[] ids)
{
  return View(ids);
}
like image 411
Pavel Shkleinik Avatar asked Dec 24 '11 16:12

Pavel Shkleinik


1 Answers

+ is a reserved symbol in an url. It means white space. So to achieve what you are looking for you could write a custom model binder:

public class StringModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value != null && !string.IsNullOrEmpty(value.AttemptedValue))
        {
            return value.AttemptedValue.Split(' ');
        }
        return base.BindModel(controllerContext, bindingContext);
    }
}

and then either register it globally for the string[] type or use the ModelBinder attribute:

public ActionResult MyActionName(
    [ModelBinder(typeof(StringModelBinder))] string[] ids
)
{
    return View(ids);
}

Obviously if you want to use an url of the form /MyControllerName/MyActionName/Id1+Id2+Id3+Id4 that will bind the last part as an action parameter called ids you will have to modify the default route definition which uses {id}.

like image 175
Darin Dimitrov Avatar answered Nov 15 '22 08:11

Darin Dimitrov