Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
    {
        this.Clients = new List<Client>();
    }

    public int Id { get; set; }
    public string JId { get; set; }
    public string Name { get; set; }
    public string CompanyId { get; set; }
    public virtual Company Company { get; set; }
    public virtual ICollection<Client> Clients { get; set; }
}

My Controllers :

    [Authorize]
    public ActionResult Action()
    {
        var books = GetBooks();
        ViewBag.Books = new SelectList(books);
        return View();
    }

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

My Form :

@using (Html.BeginForm("Journaux","Company"))
{
<table>
    <tr>
        <td>
            @Html.DropDownList("book", (SelectList)ViewBag.Books)
        </td>
    </tr>
    <tr>
        <td>
            <input type="submit" value="Search">
        </td>
    </tr>
</table>
}

When I click, the parameter 'book' in the Action is always null. What am I doing wrong?

like image 332
Azzedine Hassaini Avatar asked Apr 08 '13 14:04

Azzedine Hassaini


1 Answers

You can use DropDownListFor as below, It so simpler

@Html.DropDownListFor(m => m.Id, new SelectList(Model.Books,"Id","Name","1"))

(You need a strongly typed view for this -- View bag is not suitable for large lists)

   public ActionResult Action(Book model)
   {
        if (ValidateFields()
        {
            var Id = model.Id;
        ...        

I think this is simpler to use.

like image 68
mesut Avatar answered Oct 23 '22 19:10

mesut