I am using ASP.NET Core 3.1 MVC to create a page with a form. The dropdown is populated with data from the database. In my controller, I want to capture the text of the selected item from the dropdown. Right now I am able to capture the ID associated with the selected item.
My Model:
public int ID { get; set; }
public string bookName { get; set; }
public string Author { get; set; }
My cshtml:
<form method="post" asp-controller="Index" asp-action="Index" role="post">
<div class="form-group">
<label asp-for="bookName"></label>
<select name="bookName" asp-items="@(new SelectList(ViewBag.message, "ID", "bookName"))"></select>
</div>
</form>
My Controller:
public void PopulateBooks()
{
List<bookModel> bookName = new List<bookModel>();
bookName = (from a in _context.bookModel select a).ToList();
bookName.Insert(0, new bookModel { ID = 0, bookName = "" });
ViewBag.message = bookName;
}
[HttpPost]
public async Task<IActionResult> Index([FromForm] bookModel model)
{
string bookName = HttpContext.Request.Form["bookName"];
}
My string variable "bookName" returns the ID with the selected book, but I want the name of the selected book. Thanks!