0

This might seem a pretty simple question;

I'm using the Pubs database with the Authors table. I have used Linq to SQL as my data access and I've created an edit view with ASP.net MVC. The last property of an author model is 'contract' which is a true/false value. What I am attempting to do is to create a DropDownList with the values 'yes' or 'no' and bind to that list when the pages loads with the value from the authors model.

Here is what I have for the DropDownList markup:

Html.DropDownList("dropDownList", new[]
{                        
   new SelectListItem { Text = "Yes", Value = "true" }, 
   new SelectListItem { Text = "No", Value = "false" } 
})

The view model comes back as this:

 model.contract

which is a boolean value of 'true' or 'false'.

What would be the easiest way set the correct value in the dropdown list using the model's value?

Answer

Instead of using just :

model.contract

I went ahead and used:

Model.contract 

Which accessed the page level model which is where I needed to be. After that everything else came together.

Chris
  • 6,272
  • 9
  • 35
  • 57

1 Answers1

1

i would consider using checkbox than drowpdown list:

@Html.CheckBox("checkbox", model.contract)

if you still want to use dropdown list try this:

Html.DropDownList("dropDownList", new[]
{                        
   new SelectListItem { Text = "Yes", Value = "true", Selected = ( model.contract == true) }, 
   new SelectListItem { Text = "No", Value = "false", Selected = ( model.contract == false )} 
})
meeron
  • 26
  • 1
  • 1
    This is correct. I would probably go with shorthand bool; `model.contract` and `!model.contract` for the `Selected` indicator. Make sure your view inherits with the model class. `Inherits=System.Web.Mvc.ViewPage` – Nathan Jan 31 '11 at 21:33
  • Everything was correct except I needed to access the Page level Model. Going from lower case 'm' to upper case 'M' changed everything. Thanks for the help! – Chris Feb 01 '11 at 14:32
  • @Nathan, I went ahead and used the shorthand notation since it made a little more since when reading it as code. Thanks! – Chris Feb 01 '11 at 14:32