本文介绍了ASP.NET MVC-如何用另一个模型填充下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个称为PropertyModel,另一个称为PropertyTypeModel. PropertyModel包含PropertyTypeModel,如下所示:

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; }
}

PropertyTypeModel是这个:

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();
        }
    }
}

PropertyTypeModel从数据库中读取数据,并创建一个带有(现在)两个值"house"和"apartment"的列表.在视图中,我需要从dropdownlist中选择属性类型,我唯一能做到的方法就是直接将列表硬编码到视图中,如下所示:

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") %>

我不希望这样做,因为在数据库中进行的任何更改(例如添加另一种类型的属性)都意味着在视图中重新编码列表.此外,这段代码是这样给我的,我需要使用PropertyTypeModel.

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.

我的问题是:如何用PropertyTypeModel PropertyTypeSelectList填充dropdownlist?我尚未找到有关如何实现此目标的任何信息.如何将类型模型读取"到属性模型中?

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.

推荐答案

您尝试过

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

这篇关于ASP.NET MVC-如何用另一个模型填充下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 22:27