我在将选中的复选框放入我的 mvc 控制器并将它们保存在数据库中时遇到问题。我在创建视图中为每个循环生成了我的列表。
我的广告类:
public class Advert
{
public int AdvertId { get; set; }
public int SponsorId { get; set; }
[DisplayName("Amount")]
public int Amount { get; set; }
[DisplayName("Start date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yy}")]
[DataType(DataType.Date)]
public System.DateTime StartDate { get; set; }
[DisplayName("End date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yy}")]
public DateTime EndDate { get; set; }
public List<Continent> Continents { get; set; }
public List<Country> Countries { get; set; }
public List<Sport> Sports { get; set; }
public Gender Gender { get; set; }
public Sponsor Sponsor { get; set; }
public int SponsorTypeId { get; set; }
}
(部分)创建视图
<div class="editor-label">
@Html.LabelFor(model => model.SponsorId, "Select sport")
</div>
<div class="editor-field">
@foreach (var item in Model.Sports)
{
<tr>
<td>
<input type="checkbox" id="@item.SportId" name="SelectedSport" value="@item.SportId"/>
</td>
<td>
@item.SportName
</td>
</tr> <br />
}
</div>
广告控制器
// POST: /Advert/Create
[HttpPost]
public ActionResult Create(Advert advert)
{
ViewBag.SponsorId = new SelectList(db.Sponsors, "SponsorId", "SponsorCompany", advert.SponsorId);
advert.SponsorTypeId = service.sponsorType(advert.Amount);
if (ModelState.IsValid)
{
db.Adverts.Add(advert);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(advert);
}
我真的在这一点上停留了一段时间,所以欢迎任何帮助!