我是MVC的新手。我的方法中有以下代码:
// Get list of news formats that were ticked
IEnumerable<int> newsFormatIds = viewModel.ClubNewsFormats
.Where(c => c.selected == true).
Select(c => c.NewsFormatId);
// Copy news formats
IEnumerable<ClubNewsFormat> clubNewsFormats = club.ClubNewsFormats.ToList();
// Remove previous formats
foreach (ClubNewsFormat previousClubNewsFormats in clubNewsFormats)
{
db.ClubNewsFormats.Remove(previousClubNewsFormats);
}
// Add new club news formats
foreach (int NewsFormatId in newsFormatIds)
{
NewsFormat newsFormat = db.NewsFormats.Find(NewsFormatId);
var newClubNewsFormat = new ClubNewsFormat {
ClubId = club.ClubId,
NewsFormatId = newsFormat.NewsFormatId,
Discount =
};
db.ClubNewsFormats.Add(newClubNewsFormat);
}
它获取视图中勾选的项目列表,然后将每个项目的记录添加到ClubNewsFormats表中。通过使用IEnumerable生成所有Model.ClubNewsFormats [c] .NewsFormatId的列表,其中Model.ClubNewsFormats [c] .selected为true。除了能够选择ID之外,您还可以为每个Id添加折扣。我希望能够在将每个选定ID保存到ClubNewsFormats表时为其提交此折扣值。
如何将Discount添加到IEnumerable以及Id以便我可以在foreach(newsFormatIds中的int NewsFormatId)循环中提交它?
视图的部分是:
@for (int c = 0; c < Model.ClubNewsFormats.Count(); c++)
{
<div>
@Html.HiddenFor(x => Model.ClubNewsFormats[c].NewsFormatId)
@Html.CheckBoxFor(x => Model.ClubNewsFormats[c].selected)
@Html.LabelFor(x => Model.ClubNewsFormats[c].Format, Model.ClubNewsFormats[c].Format)
@Html.EditorFor(x => Model.ClubNewsFormats[c].Discount)
</div>
}
视图模型是:
public class ClubNewsFormatsViewModel
{
public int NewsFormatId { get; set; }
public string Format { get; set; }
public bool selected { get; set; }
[Display(Name = "Discount")]
public decimal Discount { get; set; }
}
在主视图模型中引用:
public ClubNewsFormatsViewModel[] ClubNewsFormats { get; set; }
答案 0 :(得分:0)
我修改了控制器:
// Remove previous formats
foreach (ClubNewsFormat previousClubNewsFormats in clubNewsFormats)
{
db.ClubNewsFormats.Remove(previousClubNewsFormats);
}
// Add new club news formats
foreach (ClubNewsFormatsViewModel clubNewsFormat in viewModel.ClubNewsFormats.Where(c => c.selected == true))
{
var newClubNewsFormat = new ClubNewsFormat { ClubId = club.ClubId, NewsFormatId = clubNewsFormat.NewsFormatId, Discount = clubNewsFormat.Discount };
db.ClubNewsFormats.Add(newClubNewsFormat);
}