开发者

asp.net mvc controller arguments a?b1,c2... how to parse variable number?

If a URL, in asp.net mvc, has args that are not catered for in the index/show method signature of a controller, is it possible to use something like a params string[] args in the signature to gather them up. Or what is a good way to do this when the arg is a list of separated values (ie not name/value pairs)?

We have users, ultimately, creating urls with a variable number of arguments & need to parse them.

This is the code we have at the moment, but we can't help thinking there's a better way without splitting the开发者_Go百科 string ourselves:

var url = Request.RawUrl.Split('?');

   if (url.Length > 1)
   {
     var queryString = url[1];
     var queryStringArgs = queryString.Split('&');
     var queryStringMembers = from arg in queryStringArgs
             let c = arg.Split('=').Length == 1
             where c 
             select arg;
     ViewBag.QueryStringMembers = queryStringMembers.ToJson();    
   }

*Append: these args dont have name=value, it's just a list of values. Request.QueryString doesn't seem to help us, as it treats these query string args differently because they are not name=value, they are just value. So it puts them in a Request.QueryString[null] key as comma separated


First things first what you have is a malformed URL. So you are totally on your own parsing it. You may also expect it to fail any time. Everything that is part of the querystring, i.e. following the first ?, must be url encoded, you should not have multiple ?.

This being said you could write a custom model binder:

public class CustomModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var tokens = controllerContext.HttpContext.Request.RawUrl.Split('?');
        if (tokens.Length > 1) 
        {
            return tokens.Skip(1).ToArray();
        }
        return null;
    }
}

and then:

public ActionResult Index([ModelBinder(typeof(CustomModelBinder))]string[] args)
{
    return View();
}


Request.QueryString.AllKeys will contain a string array of the argument names sent in on the QueryString. Is that what you're looking for?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜