dumbfreak
dumbfreak

Reputation: 37

ASP.NET MVC - How to populate dropdownlist with another model?

one is called PropertyModel and the other is called PropertyTypeModel. The PropertyModel contains a PropertyTypeModel as you can see next:

public class PropertyModel  {
    public int PropertyID { get; set; }

    public PropertyTypeModel PropertyType { get; set; }

    [DataType(DataType.Text)]
    [DisplayName("Property name")]
    public string PropertyName { get; set; }
}

The PropertyTypeModel is this:

public class PropertyTypeModel {
    public int PropertyTypeID { get; set; }
    [DataType(DataType.Text)]

    [DisplayName("Property type")]
    public string PropertyType { get; set; }

    public static List<SelectListItem> PropertyTypeSelectList()
    {
        using (Properties dataContext = new Properties())
        {
            return (from pt in dataContext.PropertyTypes
                    select new SelectListItem
                    {
                        Value = pt.PropertyTypeID.ToString(),
                        Text = pt.PropertyTypeName
                    }).ToList();
        }          
    }
}

The PropertyTypeModel reads from the database, and creates a list with (for now) two values, "house" and "apartment". in the view, where i need to select the property type from a dropdownlist, the only way i've been able to do so is by hardcoding the list straight into the view, like so:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<PropertyApplication.Models.PropertyModel>" %>
....
....
<%= Html.DropDownListFor(m => m.PropertyType.PropertyType,  new[] {
new SelectListItem { Text = "House",
Value = "House" },
new SelectListItem { Text = "Apartment",
Value = "Apartment" }
}
, "Choose one") %>

I don't want this, since any changes made in the database, such as adding another type of property will mean re-coding the list in the view. besides, this code was given to me like this, and I NEED to use the PropertyTypeModel.

My question is: How do i populate the dropdownlist for with the PropertyTypeModel PropertyTypeSelectList? I haven't been able to find any info on how to achieve this. How to "read" the type model into the property model?

Please help, i've been at this for hours. If possible at all, the code to do so, that would be great.

Upvotes: 1

Views: 3538

Answers (1)

Dirk
Dirk

Reputation: 3093

Have you tried

<%= Html.DropDownListFor(m => m.PropertyType.PropertyType,  Model.PropertyType.PropertyTypeSelectList(), "Choose one") %>

Upvotes: 1

Related Questions