Two easy ways to resolve the failure in SelectedValue in MVC DropDownList
Two easy ways to resolve the failure in SelectedValue in MVC DropDownList
Scaffolding my Net Core project using Visual Studio 2017 :
Model
public class Site
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Lease> Leases { get; set; }
}
public class Lease
{
public int Id { get; set; }
public string Name { get; set; }
public int SiteId { get; set; }
public virtual Site Site { get; set; }
}
Create.cshtml
<select asp-for="SiteId" class="form-control" asp-items="ViewBag.SiteId">
<option>Please select site</option>
</select>
LeasesController.cs
// GET: Leases/Create
public async Task<IActionResult> Create(int? defaultSiteId)
{
ViewData["SiteId"] = new SelectList(await GetSiteSelectList(), "Id", "Name", defaultSiteId);
var lease = new Lease()
{
Site = await GetSiteById(defaultSiteId) // this line has nothing to do with dropdownlist
};
return View(lease);
}
public async Task<dynamic> GetSiteSelectList()
{
return (await _context.Sites.ToListAsync()).Select(s => new {
Id = s.Id,
Name= s.Id+ " - " + s.Name
});
}
Run as /leases/Create?defaultSiteId=2, the dropdownlist displays as expected:
1 - Downtown Office
2 - North Building
3 - South Land
<select asp-for="SiteId" class="form-control" asp-items="ViewBag.SiteId">
<option>Please select site</option>
</select>
{
};
return View(lease);
Run as /leases/Create?defaultSiteId=2, the dropdownlist displays as expected:
1 - Downtown Office
2 - North Building
3 - South Land
However, the default site 2 is not selected.
Solution 1
<select asp-for="SiteId" class="form-control" asp-items="ViewBag.SiteId">
<option>Please select site</option>
</select>
Preset lease's SiteId and pass this lease to view:
ViewData["SiteId"] = new SelectList(await GetSiteSelectList(), "Id", "Name", defaultSiteId);
var lease = new Lease(){
SiteId = defaultSiteId.Value, // add this line !
Site = await GetSiteById(defaultSiteId)};
return View(lease);
See: https://stackoverflow.com/questions/42503172/c-sharp-mvc-6-dotnet-core-select-with-selected-option-not-selecting
Solution 2
Use DropDownList instead of asp-items:
@Html.DropDownList("SiteId", "Please select site", new { @class = "form-control" })
Note: SiteId is the bound to field: DropDownList("SiteId") will look for ViewBag.SiteId (the same name as the boud field) for SelectList
ViewData["SiteId"] = new SelectList(await GetSiteSelectList(), "Id", "Name", defaultSiteId);
var lease = new Lease()
{
return View(lease);
{
Site = await GetSiteById(defaultSiteId)
};return View(lease);
https://www.mikesdotnetting.com/article/128/get-the-drop-on-asp-net-mvc-dropdownlists
http://www.c-sharpcorner.com/UploadFile/ff2f08/anonymous-types-in-C-Sharp/
Comments
Post a Comment