开发者

How to setup an asp.net mvc route with two optional parameters, one being a paramarray value?

I want to make the following开发者_Python百科 asp.net mvc routes:

http://somedomain.com/user/search/500?Users=1,2,3,4
http://somedomain.com/user/search/500
http://somedomain.com/user/search?Users=1,2,3,4
http://somedomain.com/user/search

User would match to the controller, search would match to the action method. The optional parameter 500 would match to you guessed it an optional parameter in the action method. The optional querystring of Users would match to an optional array parameter in the action method.

What would be the best way going about setting these up? A custom ActionFilterAttribute? Two different action methods? Multiple route entries in my routescollection?

Any info would be greatly appreciated.


I would define the following route:

routes.MapRoute(
    "Default",
    "{controller}/{action}/{someparam}",
    new { controller = "Users", action = "Search", id = UrlParameter.Optional }
);

and then write a custom model binder for a string array:

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

finally I would have the controller action defined like this:

public ActionResult Search(
    [ModelBinder(typeof(StringArrayModelBinder))] string[] users, 
    string someparam
)
{
    ...
}

and if you wanted this custom model binder to apply to all actions that have an array of string as action argument you could declare it in Application_Start:

ModelBinders.Binders.Add(typeof(string[]), new StringArrayModelBinder());

and then your controller action will simply become:

public ActionResult Search(string[] users, string someparam)
{
    ...
}


I ended up creating a custom actionfilterattribute that took the querystring Users from the request and converted it into a list of longs which i then placed into an actionparameter. The parameter for 500 was simply set to optional in both the route and the actionmethod.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜