Click here to Skip to main content
15,881,850 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have 3 classes.

Person, Address, Country.

Person n:1 Address
Address n:1 Country.

my EF model is working correctly but...

when i use scaffolding to generate my Address views it works.

and

when i use scaffolding to generate my Person and manually add the address fields.

the dropdownlist doesnt work.

when i check my model in debugmode, the CountryId is = 0.

what can i do?

srry if my englitch is terrible bad im a little noobie


<div class="form-group">
    @Html.LabelFor(model => model.Address.IdCountry, "IdCountry", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("IdCountry", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Address.IdCountry, "", new { @class = "text-danger" })
     </div>
</div>
Posted
Updated 14-Jan-16 4:20am
v4
Comments
Nathan Minier 14-Jan-16 7:42am    
Use the "Improve Question" link and add in the Razor which has your dropdown and the action that populates it. We can start from there.
Icc Angel Guillermo Coeto Roque 14-Jan-16 9:24am    
tankyou there is my code i really apreciate your help
John C Rayan 14-Jan-16 10:31am    
Your action method code will help us.

1 solution

Okay, CountryId is coming through as 0 since that's the default value for an int value (or is it supposed to be IdCountry, as that's shown in your code).

You'll want to use a slightly different helper class, the Html.DropDownListFor(). It should look like this:

C#
@Html.DropDownListFor(model => model.IdCountry, Model.mySelectListItems, new { @class = "form-control" })


Now, you'll need to make a couple of changes on the model side. Since I don't know your model name, I'll just call it ViewModel:

C#
public class ViewModel
{
   ...
   public IEnumerable<selectlistitem> mySelectListItems
   ...
}
</selectlistitem>


And finally, since I don't know how you're building your ViewModel, we'll look at a controller-based implementation:

C#
public ActionResult MyViewAction()
{
   ...
   // After the ViewModel object has been created
   ViewModelInstance.mySelectListItems = 
      MyDbContext.Countries.Select(x => 
         new SelectListItem { 
            Value = x.Id, 
            Text = x.Name 
      }).ToArray();
   ...
}


There is a fairly comprehensive walkthrough at:
DropDownListFor with ASP.NET MVC[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900