我在使用 ViewBag 列表和我的模型从 DropDownListFor 获取数据时遇到问题。这是我的控制器代码:[HttpGet]public ActionResult JoinTeam(){ var TeamList = _db.TeamModels.ToList(); SelectList list = new SelectList(TeamList, "Id", "TeamName"); ViewBag.TeamList = list; return View();}Razor 视图表单如下所示:@using (Html.BeginForm("JoinTeam", "Home", FormMethod.Post)){ @Html.TextBoxFor(m => m.DisplayName, new { @class = "form-control form-control-lg", placeholder = "Enter your Battle Net ID" }) <br/> @Html.DropDownListFor(m => m.TeamModel, (SelectList)ViewBag.TeamList, "- Select a Team to Join -", new { @class= "form-control form-control-lg" }) <br /> <button type="submit" class="btn btn-primary" style="width:100%;text-align:center;">Submit</button>}TextBoxFor 助手正确返回数据,但我在下拉列表中选择的任何选项都不会传递到我的 post 方法中。有没有人有任何想法?post 操作确实有效,因为它从模型中获取 TextBoxFor 帮助的数据,但它看起来像这样: [HttpPost] public async Task<ActionResult> JoinTeam(GuardianModel model) { try { string BNETId = model.DisplayName.Replace("#", "%23"); long memberId = 0; if (ModelState.IsValid) { Bungie.Responses.SearchPlayersResponse member = await service.SearchPlayers(MembershipType.Blizzard, BNETId); memberId = member[0].MembershipId; } using (var context = new CoCodbEntities1()) { var g = new GuardianModel { MembershipId = memberId.ToString(), DisplayName = BNETId, MembershipType = 4, TeamID = model.TeamModel.Id }; TempData["UserMessage"] = ViewBag.TeamList.Id; return RedirectToAction("Success"); } } catch { } return View(); }
2 回答
小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
从你分享的截图来看,TeamModel
property 是 type 的虚拟导航属性TeamModel
。你不应该担心加载它。所有你需要担心加载外键属性值(通常是一个简单的类型,比如一个int
左右。
您的 SELECT 元素名称应该是TeamID
. 提交表单时,它会将选定的选项值映射到TeamID
模型的属性值,即外键属性。
@Html.DropDownListFor(m => m.TeamID, (SelectList)ViewBag.TeamList, "- Select a Team to Join -", new { @class= "form-control form-control-lg" })
虽然这可能会解决问题,但最好使用视图模型而不是使用实体类。
- 2 回答
- 0 关注
- 222 浏览
添加回答
举报
0/150
提交
取消