基于用户的数据表中的 Razor 形式的 DropdownListFor

DropdownListFor in Razor form from datatable based on user

我需要一些关于此下拉列表的帮助。我有一个表格,我希望客户的位置是 select 项目。我有一个视图模型,它填充了我需要的所有内容,但我想让位置 select 可用。每个客户应该至少有 1 个条目,所以在我看来,在填充下拉列表之前,我可能需要使用 "if" 语句进行计数,如果只有 1 个,则只需将其用作 EditorFor。正在从地址 table 中提取位置,同时从客户 table 中提取客户名称。

我试过

ViewBag.Locations = new SelectList(db.Addresses, "AddressId", "LocationName");

但是当前的模型设置是从地址 table 中获取的,并且该列不是 IEnumerable SelectList。下面是我的模型:

public class AddEventViewModel
{
    public static AddEventViewModel GetCustomerInfo(string userId, CustomerEntities db)
    {
        var QCustInfo = from ad in db.Addresses
                        join ua in db.UserToAddresses on ad.AddressId equals ua.AddressId
                        join cus in db.CustomerNames on ad.CustomerId equals cus.CustomerId
                        where (ua.UserId == userId)
                        select new AddEventViewModel
                        {
                            CustomerId = cus.CustomerId,
                            CustomerName = cus.CustomerName,
                            Location = ad.LocationName
                        };
        var result = QCustInfo.SingleOrDefault();

        return result;
    }

    public int CustomerId { get; set; }
    [Display(Name = "Location Name")]
    public string Location { get; set; }
    public bool AllDay { get; set; }
    [Display(Name ="Title")]
    public string Title { get; set; }
    [Display(Name = "Description")]
    public string Description { get; set; }
    [DataType(DataType.DateTime), Required]
    [DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}", ApplyFormatInEditMode = true)]
    [Display(Name = "Start Date")]
    public DateTime StartDate { get; set; }
    [DataType(DataType.DateTime), Required]
    [DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}", ApplyFormatInEditMode = true)]
    [Display(Name = "End Date")]
    public DateTime EndDate { get; set; }
    [Display(Name = "Customer Name")]
    public string CustomerName { get; set; }

    public virtual CustomerNames Customer { get; set; }
    public virtual IEnumerable<Addresses> Addresses { get; set; }

该表格只是一个包含字段和作品的基本表格我只需要位置 select 可用。制作另一个 viewModel 似乎不是我当前设置的方式,因为它正在与实际的 table 模型进行连接。感谢您的帮助。

原来我需要做的就是添加。

new SelectList(Model.Addresses, "AddressId", "LocationName"),

到Html.DropdownListFor 顶部的代码没有改变。这是完整的字符串。

 @Html.DropDownListFor(model => model.Location, new SelectList(Model.Addresses, "AddressId", "LocationName"), new { htmlAttributes = new { @class = "form-control" } })