Bru*_*ero 13 c# dictionary mvccontrib asp.net-mvc-3
我有以下问题:我在最重要的功能中工作的系统之一是搜索页面.在这个页面中,我有一些选项,如每页记录,开始日期,结束日期和有问题的一个:类型.必须有可能选择多种类型(大多数时候,所有这些都将被选中).为了完成这项工作,我创建了以下内容:
<div>
<label>Eventos:</label>
<div>
@Html.ListBox("events", Model.Events, new { style = "width: 100%" })
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
它创建了一个列表框,我可以在其中选择多个选项,当表单被提交时,我的查询字符串将如下所示:
/ 10?周期= 9&事件= 1&事件= 3&recordsPerPage = 10
在那里可以看到创建了两个事件(这是我以前说过的类型).此页面的操作方法将其List<long>
作为其参数之一,表示两个events
值.当我想在MVC Contrib中使用它时,问题就开始了.他们的寻呼机工作得很好,但正如我的要求,我创建了另一个寻呼机,它显示了用户所在之前和之前五页的链接.为此,在我的代码的一部分中,我必须执行以下操作(这与MVC Contrib寻呼机非常相似,有效):
public RouteValueDictionary GetRoute(int page)
{
var routeValues = new RouteValueDictionary();
foreach (var key in Context.Request.QueryString.AllKeys.Where(key => key != null))
{
routeValues[key] = Context.Request.QueryString[key];
}
routeValues["page"] = page;
return routeValues;
}
Run Code Online (Sandbox Code Playgroud)
然后:
@Html.ActionLink(page.ToString(), action, controller, GetRoute(page), null)
Run Code Online (Sandbox Code Playgroud)
问题是它是一个字典,它第二次设置routeValues["events"]
擦除前一个的值.
你们对如何使用它有什么想法吗?
很好的问题。不幸的是,使用Html.ActionLink
帮助程序生成具有多个同名查询字符串参数的 url 并不容易。所以我可以看到两种可能的解决方案:
编写一个自定义模型绑定器long[]
,它能够解析逗号分隔的值。这样,您就可以让您的GetRoute
方法,这将产生以下网址:period=9&events=1%2C3&recordsPerPage=10&page=5
。
public class CommaSeparatedLongArrayModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (values != null && !string.IsNullOrEmpty(values.AttemptedValue))
{
// TODO: A minimum of error handling would be nice here
return values.AttemptedValue.Split(',').Select(x => long.Parse(x)).ToArray();
}
return base.BindModel(controllerContext, bindingContext);
}
}
Run Code Online (Sandbox Code Playgroud)
您将注册Application_Start
:
ModelBinders.Binders.Add(typeof(long[]), new CommaSeparatedLongArrayModelBinder());
Run Code Online (Sandbox Code Playgroud)
然后下面的控制器动作将能够理解之前的 URL:
public ActionResult Foo(long[] events, int page, int period, int recordsPerPage)
{
...
}
Run Code Online (Sandbox Code Playgroud)手动生成这个锚点:
<a href="@string.Format("{0}?{1}&page=5", Url.Action("action", "controller"), Request.QueryString)">abc</a>
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
3592 次 |
最近记录: |