简体   繁体   中英

How to change drop-down list on select

I have a dropdownlist that is being populated by a sql server, I am using Visual Studio 2010, cshtml, with razor as well as using the MVC pattern to create this project. What I am trying to do is when someone selects a value from the dropdown list on change it will update the page with information about that book.

I need help with the three things below:

  1. user selects a book from the dropdownlist how to get the Book Name back to the controller
  2. The server (retrieve the information from the server about the book) and
  3. Back to view to be displayed.

I started with getting the dropdown poplulated.

My View looks like this

BookName: @Html.DropDownList("BookName", ViewData["BookName"] as IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })

My Controller:

public ActionResult Index()
    {
       ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());
                    return View();
    }

A dropdown list can't cause the page to post back to your controller on its own. You need to do one of two things:

  1. Add a submit button so that the user changes the dropdown and then clicks a button to view the results.
  2. Use javascript to submit the form on the element's change event.

Either way, you will need to wrap the dropdown/submit button in a form.

Option 1

<form>
    BookName: @Html.DropDownList("BookName", ViewData["BookName"] as  IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
    <input type="submit" value="Show results" />
</form>

Option 2

<script type="text/javascript">
    // assuming you're using jQuery
    $(function() {
        $('#UserSelectedValue').change(function() {
            $(this).parent('form').submit();
        });
    });
</script>    
<form>
    BookName: @Html.DropDownList("BookName", ViewData["BookName"] as  IEnumerable<SelectListItem>, new { id = "UserSelectedValue" })
    <input type="submit" value="Show results" />
</form>

Your controller code would then become something like:

public ActionResult Index(string bookName)
{
   ViewData["BookName"] = new SelectList(_context.BookName.Select(a => a.Book_Name).Distinct());

   if (!string.IsNullOrWhiteSpace(bookName))
   {
       ViewData["Books"] = _context.BookName.Where(b => b.Book_Name == bookName).ToList();
   }
   return View();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM