使用ViewBag列表从DropDownListFor获取所选值

时间:2018-05-10 17:44:29

标签: c# asp.net-mvc

我在使用带有我的模型的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方法中。有没有人有任何想法?

后期操作确实有效,因为它从模型中获取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();
    }

These are the values getting passed into the Post action

2 个答案:

答案 0 :(得分:1)

从您分享的屏幕截图中,TeamModel属性看起来像TeamModel类型的虚拟导航属性。你不应该打扰加载它。所有你需要担心加载forign键属性值(通常是一个简单的类型,如int左右。

您的SELECT元素名称应为TeamID。提交表单时,它会将选定的选项值映射到模型的TeamID属性值,该值是外键属性。

@Html.DropDownListFor(m => m.TeamID, (SelectList)ViewBag.TeamList,
           "- Select a Team to Join -", new { @class= "form-control form-control-lg" })

虽然这可能会解决问题,但使用视图模型而不是使用实体类是个好主意。

答案 1 :(得分:0)

我发现了我遇到的问题。所有我需要传递到后期操作的是TeamModel的Id。所以我改变了这一行:

@Html.DropDownListFor(m => m.TeamModel.Id, (SelectList)ViewBag.TeamList, "- Select a Team to Join -", new { @class= "form-control form-control-lg" })

我刚刚添加了ID,它似乎有效。