我有一个对象,包含搜索,排序和分页参数以及要编辑的记录的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,因此没有嵌套,只是将所有属性都列出来。但是,这并不理想。
那么,最好的方法是什么?