[英]MVC3 Model binding pagedlist to ViewModel with custom EditorTemplate and Partial View
我试图生成一个包含在部分视图中的分页结果表。 它使用ajax调用动态刷新。
我在许多页面上重现了它,它完美地工作,但是在特定页面上,我需要绑定表行的值并使用ViewModel返回。
为了实现这一点,我尝试使用EditorTemplate来为PagedList集合使用自定义对象。 问题在于PartialView上显示的editortemplate没有为主ViewModel上的PagedList集合正确命名。
如果我用代码解释它可能更容易。
主要观点如此:
@model RequestCreateViewModel
<Code>
<div id="gridContainer">
@Html.Partial("_PagedCreateRequest")
@Html.HiddenFor(x => x.PageSize)
@Html.HiddenFor(x => x.PageNumber)
</div>
<div id="loadingContainer">
</div>
<More code>
因此,部分是:
@model IPagedList<CreateRequestModel>
<Code>
<table class="tablesorter" style="width:750px;">
<thead>
<tr>
</tr>
</thead>
<tbody>
@Html.EditorFor(x => Model)
</tbody>
</table>
</div>
<div style="float:left">
@Ajax.ImageActionLink(
"../../Content/images/first.gif",
"alt text",
"PageResults",
new
{
Page = 1,
area = "Admin",
SortBy = Model.SortBy,
SortDescending = Model.SortDescending,
PageSize = Model.PageSize
},
new
{
style = "margin-top: 2px;"
},
new
{
@readonly = "readonly"
},
new AjaxOptions
{
UpdateTargetId = "gridContainer"
}
)
</div>
+ other pager Ajax pager icons and stuff
EditorTemplate是:
@model CreateRequestModel
<tr>
<td>
@Html.CheckBoxFor(x => x.IsSelected)
</td>
<td>
@Html.DisplayFor(x => x.CompanyName)
@Html.HiddenFor(x => x.CompanyName)
</td>
<td>
@Html.DisplayFor(x => x.CompanyISIN)
@Html.HiddenFor(x => x.CompanyISIN)
</td>
<td>
@Html.DisplayFor(x => x.ShareDesc)
@Html.HiddenFor(x => x.ShareDesc)
</td>
<td>
@Html.DisplayFor(x => x.ShareClass)
@Html.HiddenFor(x => x.ShareClass)
</td>
</tr>
ViewModel是:
public class RequestCreateViewModel : ViewModelBase
{
public IPagedList<CreateRequestModel> PagedList { get; set; }
CreateRequestModel是:
public class CreateRequestModel
{
public int RequestId { get; set; }
public bool IsSelected { get; set; }
public string CompanyName { get; set; }
public string CompanyISIN { get; set; }
public string ShareDesc { get; set; }
public string ShareClass { get; set; }
}
但是当回发到控制器(代码)时:
[Authorize(Roles = "Foo")]
[HttpPost]
public ActionResult RequestCreate(RequestCreateViewModel model)
属性IPagedList未绑定到ViewModel(显然),因为EditorTemplate的命名标准是
例如:[0]。无论如何
而不是:
PagedList [0] .Whatever
我无法在ViewModel中为IPagedList实例化接口的绑定副本。 那么我如何从主视图中获取信息回到模型?
我认为自定义Model Binder可能是解决方案,但我在这方面的经验很少。 最终目的是确定表格上复选框的值。 用户将选择与否,我需要知道他们选择了什么!
非常感谢任何帮助。
看看这篇文章: http : //weblogs.asp.net/nmarun/archive/2010/03/13/asp-net-mvc-2-model-binding-for-a-collection.aspx
秘诀是在控件上生成Name作为集合名称,索引器为
<input id="Products_0__ID" name="Products[0].ID" type="text" value="1" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.