如何从url中检索参数

时间:2011-11-16 05:58:03

标签: .net asp.net-mvc url

我有以下网址:

http://localhost:58124/Tag/GetData?filter(Tag)=contains(112)&filter(Process)=contains(112)&page=0&pageSize=30

如果我宣布我的行动结果

public ActionResult GetData(int page, int pageSize)

我从参数中获取 page pageSize 的值。如何从参数中获取过滤器(标记)过滤器(过程)值?

编辑:该字符串可以包含n个这些过滤器(名称)参数。有没有办法收集它们或者我是否需要单独获取它们?

3 个答案:

答案 0 :(得分:1)

您可以通过QueryString属性访问HttpRequestBase课程的Request属性。

public ActionResult GetData(int page, int pageSize)
{
    var queryString = Request.QueryString;
    var filter = queryString["filter(Tag)"];

    ///
}

答案 1 :(得分:0)

这样做的一种方法是过滤掉以“filter”开头的参数并迭代结果。在foreach循环中,您可以将它们放入列表或其他内容中,具体取决于您计划如何使用它们。我使用System.Linq是为了方便:

using System.Diagnostics;
using System.Web.Mvc;
using System.Linq;

namespace ImgGen.Controllers
{
    public class TagController : Controller
    {
        public ActionResult GetData(int page, int pageSize)
        {
            var filters = Request.QueryString.AllKeys.ToList().Where(key => key.StartsWith("filter"));
            foreach (var filter in filters)
            {
                var value = Request.QueryString.GetValues(filter)[0];
                Debug.Print(filter + " = " + value);
            }
            return View();
        }
    }
}

希望这有帮助。

答案 2 :(得分:0)

似乎是自定义模型绑定器的一个很好的候选者:

public class FilterViewModel
{
    public string Key { get; set; }
    public string Value { get; set; }
}

public class FilterViewModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var filterParamRegex = new Regex(bindingContext.ModelName + @"\((?<key>.+)\)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        return
            (from key in controllerContext.HttpContext.Request.Params.AllKeys
            let match = filterParamRegex.Match(key)
            where match.Success
            select new FilterViewModel
            {
                Key = match.Groups["key"].Value,
                Value = controllerContext.HttpContext.Request[key]
            }).ToArray();
    }
}

将在Application_Start注册:

ModelBinders.Binders.Add(typeof(FilterViewModel[]), new FilterViewModelBinder());

然后:

public ActionResult GetData(FilterViewModel[] filter, int page, int pageSize)
{
    ...
}

自定义模型绑定器的好处在于它完全符合它的名称:自定义模型绑定,因为查询字符串参数不遵循默认模型绑定器使用的标准约定。除此之外,您的控制器操作干净简单,并且不需要依赖一些丑陋的管道代码,这显然不是控制器操作的责任。

相关问题