c# - List 中的模型项绑定
问题描述
我已经将模型传递给局部视图,然后我需要将一些文本字段绑定到视图中的模型。
@model SRINews.Domain.NewsTotal
@using (Html.BeginForm("UpdateNewsItem", "Home", FormMethod.Post))
{
<table class="table table-borderless table-cart" id="mytable" data-addclass-on-smdown="table-sm">
<tbody>
@foreach (var item in Model.items)
{
<tr class="newsRow" id="@item.ItemId">
<td class="cart-img nostretch">
<a href="#"><img src="@item.ImageUrl" alt=""></a>
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" placeholder="Personalized Name">
//@Html.TextboxFor(x=>x)
// I want to bind PersonalizedName to model
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" placeholder="Country">
// I want to bind Country to model
</td>
</tr>
}
</tbody>
</table>
<input type="submit" class="btn btn-primary" value="Personal Details" />
}
模型
public class Items
{
public int ItemId { get; set; }
public string ItemCode { get; set; }
public string PersonalizedName {get;set;}
public string Country {get;set;}
}
public class NewsTotal
{
public int BaseItem { get; set; }
public string BaseName {get;set;}
public List<Items> items { get; } = new List<Items>();
}
Public ActionResult UpdateNewsItem(NewsTotal nTotal)
{
return View();
}
解决方案
您想使用传统的 for 循环,因此您可以使用索引绑定到List<T>
模型中的您,您还需要使其items
可变,因此您还需要有一个set
for 它,否则您将不会能够提交任何东西:
//You'll need to make this mutable, so it can post the edited values
public List<Items> items { get; set; } = new List<Items>();
然后在您的视图中:
@for(int i = 0; i < Model.items.Count; i++)
{
@Html.HiddenFor(x => Model.items[i].ItemId)
@Html.HiddenFor(x => Model.items[i].ItemCode)
<tr class="shoppingCartRow" id="@Model.items[i].ItemId">
<td class="cart-img nostretch">
<a href="#"><img src="@Model.items[i].ImageUrl" alt=""></a>
</td>
</tr>
<tr>
<td>
@Html.TextboxFor(x=> Model.items[i].PersonalizedName, new { @placeholder = "Personalized Name"})
</td>
</tr>
<tr>
<td>
@Html.TextboxFor(x=> Model.items[i].Country, new { @placeholder = "Country"})
</td>
</tr>
}
推荐阅读
- types - rustc 奇怪地假设类型参数必须相同,即使它们是分开的?
- autohotkey - 如何在 Autohotkey 中通过 RegExp 匹配包含键名的字符串
- python - 带有 GUI 的键侦听器脚本不起作用 (Tkinter)
- r - 使用 Gauss-Hermite 求积评估二元正态分布
- deprecated - 在 2019 年 12 月 6 日 Google Drive Android API 关闭后,Games.Snapshots.open 和所有其他已弃用的 Games API 调用是否会继续工作?
- amazon-web-services - 放置存储桶策略时访问被拒绝
- python - 使用两个整数变量之间差异的逻辑
- node.js - 如何使用 emscripten 通过 node.js 进行文件输入?
- .net - XML 使用带有导入的 XSD 进行验证,并包含在 .net 核心中
- python - 如何按整数对元组的混合列表进行排序?