【发布时间】:2014-07-07 17:40:04
【问题描述】:
我有一个对象,其中包含搜索、排序和分页参数以及要编辑的记录的 id。
我想将此对象作为路由值对象传递给 Html.ActionLink(),以便生成的查询字符串将由默认模型绑定器正确映射到 Edit 操作的参数,即 EditViewModel。
想法是在Edit动作完成后,它可以重定向回Index并保持相同的分页/排序位置,在相同的数据集中,并由相同的搜索字符串过滤。
编辑视图模型:
public class EditViewModel
{
public SearchSortPageViewModel SearchSortPageParams { get; set; }
public int Id { get; set; }
public EditViewModel()
{
SearchSortPageParams = new SearchSortPageViewModel();
Id = 0;
}
public EditViewModel(SearchSortPageViewModel searchSortPageParams, int id)
{
SearchSortPageParams = searchSortPageParams;
Id = id;
}
}
public class SearchSortPageViewModel
{
public string SearchString { get; set; }
public string SortCol { get; set; }
public string SortOrder { get; set; }
public int Page { get; set; }
public int PageSize { get; set; }
}
编辑操作:
public ActionResult Edit(EditViewModel evm)
{
/* ... */
}
当我在视图中这样做时:
@model MyApp.Areas.Books.ViewModels.Books.IndexViewModel
...
@{EditViewModel evm = new EditViewModel(Model.SearchSortPageParams, item.ID);}
@Html.ActionLink("Edit", "Edit", evm)
我明白了:
http://localhost:63816/Books/Books/Edit/4?SearchSortPageParams=MyApp.Areas.Base.ViewModels.SearchSortPageViewModel
但我想要这个:
http://localhost:63816/Books/Books/Edit/4?SearchSortPageParams.SearchString=abc&SearchSortPageParams.SortCol=name&SearchSortPageParams.SortOrder=asc&SearchSortPageParams.Page=1&SearchSortPageParams.PageSize=3
到目前为止,我能够传递对象的唯一方法是手动准备查询字符串,如下所示:
@{string theQueryString = "?SearchSortPageParams.SearchString=" + @evm.SearchSortPageParams.SearchString + "&SearchSortPageParams.SortCol=" + @evm.SearchSortPageParams.SortCol + "&SearchSortPageParams.SortOrder=" + @evm.SearchSortPageParams.SortOrder + "&SearchSortPageParams.Page=" + @evm.SearchSortPageParams.Page + "&SearchSortPageParams.PageSize=" + @evm.SearchSortPageParams.PageSize;}
<a href="@Url.Action("Edit", new { evm.Id })@(theQueryString)">Edit</a>
我曾想过编写一个自定义模型绑定器,但考虑到默认模型绑定器已经处理嵌套对象(如果以它期望的方式格式化为查询字符串),这似乎很愚蠢。
我还想过编写一个自定义对象序列化器,它输出默认模型绑定器期望的序列格式,但还没有走这条路。
最后,我想到了将 EditViewModel 展平,因此没有任何嵌套,只是将所有属性展平。但是,这并不理想。
那么,最好的方法是什么?
【问题讨论】:
标签: asp.net-mvc model-binding html.actionlink