gpt4 book ai didi

asp.net-mvc-3 - MVC3 Razor 模型绑定(bind)器和继承的集合

转载 作者:行者123 更新时间:2023-12-04 16:01:29 24 4
gpt4 key购买 nike

我希望我不会在这里遗漏一些非常明显的东西,但是为什么模型绑定(bind)器总是无法绑定(bind)从集合继承的 View 模型?

假设我想显示一个分页列表并显示一个组合框并在其上方添加按钮(处理简单列表)。涉及的类(class)如下所示:

public class PagedList<T> : List<T>
{
public int TotalCount { get; set; }
}

然后是一个看起来像这样的 View 模型:
public class MyViewModel : PagedList<ConcreteModel>
{
public IEnumerable<ChildModel> List { get; set; }
public int? SelectedChildModelId { get; set; }
}

所以在 View (Razor)中:
@model MyViewModel 
@using (Html.BeginForm())
{
@Html.DropDownListFor(model => model.SelectedChildModelId, new SelectList(Model.List, "ChildModelId", "DisplayName"))
}

和 Controller HttpPost Action :
public ActionResult(MyViewModel viewModel)
{
...
}

以上将导致 ActionResult 中的 viewModel 为空。有什么合乎逻辑的解释吗?据我所知,它仅适用于从集合继承的 View 模型。

我知道我可以使用自定义绑定(bind)器解决它,但所涉及的属性是原始类型,甚至没有任何泛型或继承。

我重新设计了 View 模型,将集合继承类型作为属性,从而解决了这个问题。但是,我仍然对粘合剂为什么会在它上面分解而摸不着头脑。任何 build 性的想法表示赞赏。

最佳答案

回答我自己的问题:我所有与集合有关的模型不再从通用列表或类似列表继承,而是具有所需集合类型的属性。这效果更好,因为在渲染时您可以使用

@Html.EditorFor(m => m.CollectionProperty)

并在 Views/Shared/EditorTemplates 下为包含的类型创建一个自定义编辑器。它还可以很好地与模型绑定(bind)器一起使用,因为集合中的所有单个项目都会获得一个索引,并且绑定(bind)器能够在提交时自动绑定(bind)它。

经验教训:如果您打算在 View 中使用模型,请不要从集合类型继承。

关于asp.net-mvc-3 - MVC3 Razor 模型绑定(bind)器和继承的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6427712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com