Reputation: 35
I'm having trouble getting the data from a DropDownListFor using a ViewBag list with my model. Here is my Controller code:
[HttpGet]
public ActionResult JoinTeam()
{
var TeamList = _db.TeamModels.ToList();
SelectList list = new SelectList(TeamList, "Id", "TeamName");
ViewBag.TeamList = list;
return View();
}
And the Razor view form looks like this:
@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>
}
The TextBoxFor helper is returning the data correctly, but whatever option I have selected in the drop down does not get passed into my post method. Does anyone have any ideas?
The post action does work as it's getting the data from the model for the TextBoxFor help, but here's what it looks like:
[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
Upvotes: 0
Views: 831
Reputation: 218722
From the screenshot you shared, it looks like TeamModel
property is the virtual navigational property of type TeamModel
. You should not bother about loading that. All you need to worry about loading the forign key property value (usually a simple type like an int
or so.
Your SELECT element name should be TeamID
. When the form is submitted, it will map the selected option value to the TeamID
property value of your model which is the foreign key property.
@Html.DropDownListFor(m => m.TeamID, (SelectList)ViewBag.TeamList,
"- Select a Team to Join -", new { @class= "form-control form-control-lg" })
While this might fix the issue, It is a good idea to use a view model instead of using your entity class.
Upvotes: 1
Reputation: 35
I found the issues I was having. All I needed to get passed into the post action was the Id of the TeamModel. So I changed this line:
@Html.DropDownListFor(m => m.TeamModel.Id, (SelectList)ViewBag.TeamList, "- Select a Team to Join -", new { @class= "form-control form-control-lg" })
I just added the Id and it seemed to work.
Upvotes: 0