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

三世轮回 提交于 2019-12-11 07:04:35

问题


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.


回答1:


Have you tried

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


来源:https://stackoverflow.com/questions/6794275/asp-net-mvc-how-to-populate-dropdownlist-with-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!