c# - 从 ViewModel 在 View 上创建一个自动生成的 DropDownList

标签 c# .net asp.net-mvc

我希望在 .NET MVC 中实现,但试图弄清楚如何实际执行它。目前在我的 ViewModel 上,我有(例如):

public class GroupPolicyViewModel
{
   public int PolicyId { get; set; }
   public int HistoryId{ get; set; }
   public SelectList ProductList { get; set; } // tried this
   public List<Product> ProductList1 { get; set; } // tried this
}

每当我尝试从这个 ViewModel 自动生成我的 View 时,ProductList 都会被忽略。有什么方法可以从 ViewModel 自动生成 DropDownList 吗?

最佳答案

有模型

public class GroupPolicyViewModel
{
   public int PolicyId { get; set; }
   public int HistoryId{ get; set; }
   public int SelectedProductId{ get; set; }   
   public List<Product> ProductList { get; set; } 
}

您可以创建 DropDownList

@Html.DropDownListFor(m => m.SelectedProductId, 
                  new SelectList(Model.ProductList, "ProductId", "ProductName"))

或者如果您的模型中有产品的 SelectList

@Html.DropDownListFor(m => m.SelectedProductId, Model.ProductSelectList)

如果你想要一些生成的代码,你需要使用脚手架选项来提供数据上下文类。这是很好的教程MVC Music Store

关于c# - 从 ViewModel 在 View 上创建一个自动生成的 DropDownList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14383311/

相关文章:

C#:访问修饰符使方法调用不同

c# - 当逆变导致歧义时,没有警告或错误(或运行时失败)

javascript - 用户名检查不适用于具有多个寄存器模型 (mvc) 的表单

c# - 使用 'as' 进行转换 - 为什么这不起作用?

c# - .NET 7 速率限制 - 按 IP 地址进行速率限制

LINQ 中的 C# 并行性

c# - 使用 UAC 启动时获取当前用户名

c# - 在 UserSettings 中保存 XML 数据

c# - MVC 3 注册确认邮件

c# - 使用 AutoMapper 映射 ViewModel/partials