我有强类型视图模型,我需要从用户那里获取多个强类型列表的“列表”记录。我正努力用剃须刀代码来实现这一点。这是httpget方法。
视图模型
public class AccommodationApplicationViewModel
{
public AccommodationApplicationViewModel()
{
_RentingApplicationModel = new PropertyRentingApplication();
_PropertyRentingPriceModel = new List<PropertyRentingPrice>();
_AdditionalTenantModel = new List<AdditionalTenant>();
_StudentLimitedInfoModel = new List<StudentLimitedInfo>();
}
public PropertyRentingApplication _RentingApplicationModel { get; set; }
public List<PropertyRentingPrice> _PropertyRentingPriceModel { get; set; }
public List<AdditionalTenant> _AdditionalTenantModel { get; set; }
public List<StudentLimitedInfo> _StudentLimitedInfoModel { get; set; }
}剃刀码
<div>
<div class="form-group">
@Html.LabelFor(model => model._StudentLimitedInfoModel[0].StudentNumber_UWLID, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
//@Html.EditorFor(model => model._StudentLimitedInfoModel[0].StudentNumber_UWLID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })
@Html.ValidationMessageFor(model => model._StudentLimitedInfoModel[0].StudentNumber_UWLID, "", new { @class = "text-danger" })*@
</div>
</div>我在下面一行中出现错误
@Html.EditorFor(model => model._StudentLimitedInfoModel[0].StudentNumber_UWLID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })错误是:
指数超出了范围。必须是非负的,并且小于集合的大小。参数名称:索引
发布于 2015-07-31 18:54:49
你可以采取两种方法中的一种。如果列表中有固定数量的项,您可以使用适当数量的实例来初始化它。例如:
_PropertyRentingPriceModel = new List<PropertyRentingPrice>
{
new PropertyRentingPrice(),
new PropertyRentingPrice(),
new PropertyRentingPrice()
};这会给你三个项目。然后,在你看来:
@for (var i = 0; i < Model._PropertyRentingPriceModel.Count(); i++)
{
@Html.EditorFor(m => m._PropertyRentingPriceModel[i].Foo)
}如果项目更具流动性,或者用户需要能够随意添加或删除项目,您将需要一个JavaScript解决方案,该解决方案将涉及创建输入并手动分配适当的名称。为此,我建议使用某种支持模板的数据绑定库,例如Knockout或Angular。这样做会让你的生活更轻松。在构建JavaScript模板时,只需记住收集输入名称的约定,模型绑定器将在POST请求中看到该约定:CollectionProperty[Index].Property。例如,您的输入需要如下所示:
<input type="text" name="_PropertyRentingPriceModel[0].Foo" value="" />发布于 2015-07-31 19:08:22
我不得不做一些类似的事情,最后用了一篇我找到这里的文章来做。我会发布我的实现,但我必须对它进行足够的定制,这只会混淆您要寻找的东西。
https://stackoverflow.com/questions/31748354
复制相似问题