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.

1

1 Answer 1

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 )} 
})
Sign up to request clarification or add additional context in comments.

3 Comments

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<Author>
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!
@Nathan, I went ahead and used the shorthand notation since it made a little more since when reading it as code. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.