在IEnumerable中添加然后引用多个值

本文关键字:引用 然后 IEnumerable 添加 | 更新日期: 2023-09-27 18:02:54

我是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]。[c]。Selected为true。除了能够选择Id,您还可以为每个Id添加折扣。我希望能够在将每个选定Id保存到ClubNewsFormats表时提交此折扣值。

我如何将折扣添加到IEnumerable以及Id,以便我可以在foreach (int NewsFormatId in newsFormatIds)循环中提交它?

视图的部分是:

@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; }

在IEnumerable中添加然后引用多个值

我将控制器修改为:

// 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);
     }