Get the selected value of a DropDownList. Asp.NET MVC

后端 未结 2 764
醉梦人生
醉梦人生 2020-12-11 03:21

I\'m trying to populate a DropDownList and to get the selected value when I submit the form:

Here is my model :

public class Book
{
    public Book         


        
2条回答
  •  孤街浪徒
    2020-12-11 04:03

    In HTML a dropdown box sends only simple scalar values. In your case that would be the id of the selected book:

    @Html.DropDownList("selectedBookId", (SelectList)ViewBag.Books)
    

    and then adapt your controller action so that you will retrieve the book from the id that gets passed to your controller action:

    [Authorize]
    [HttpPost]
    public ActionResult Action(string selectedBookId)
    {
        if (ValidateFields()
        {
            Book book = FetchYourBookFromTheId(selectedBookId);
            var data = GetDatasAboutBookSelected(book);
            ViewBag.Data = data;
            return View();
        }
        return View();
    }
    

提交回复
热议问题