Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从ViewModel在视图上创建自动生成的DropDownList_C#_.net_Asp.net Mvc - Fatal编程技术网

C# 从ViewModel在视图上创建自动生成的DropDownList

C# 从ViewModel在视图上创建自动生成的DropDownList,c#,.net,asp.net-mvc,C#,.net,Asp.net Mvc,我希望它能在.NETMVC中实现,但我正试图弄清楚如何真正做到这一点。当前在我的ViewModel上,我有(例如): 公共类GroupPolicyViewModel { public int PolicyId{get;set;} public int HistoryId{get;set;} public SelectList ProductList{get;set;}//尝试了此操作 公共列表ProductList1{get;set;}//尝试了此操作 } 每当我尝试从此ViewModel自动

我希望它能在.NETMVC中实现,但我正试图弄清楚如何真正做到这一点。当前在我的ViewModel上,我有(例如):

公共类GroupPolicyViewModel
{
public int PolicyId{get;set;}
public int HistoryId{get;set;}
public SelectList ProductList{get;set;}//尝试了此操作
公共列表ProductList1{get;set;}//尝试了此操作
}
每当我尝试从此ViewModel自动生成视图时,ProductList就会被忽略。是否有任何方法可以从ViewModel自动生成下拉列表?

使用model

public class GroupPolicyViewModel
{
   public int PolicyId { get; set; }
   public int HistoryId{ get; set; }
   public int SelectedProductId{ get; set; }   
   public List<Product> ProductList { get; set; } 
}
或者,如果您的型号中有产品列表

@Html.DropDownListFor(m => m.SelectedProductId, Model.ProductSelectList)
如果您想要生成一些代码,您需要使用脚手架选项来提供数据上下文类。这是一个很好的教程,您可以(从VS2010)在创建新控制器和使用实体框架时使用它。在向导中指定包含实体框架和读/写操作,向导将创建控制器和视图

它将在控制器中生成如下代码[还有更多]:

   public ActionResult Create()
    {
        ViewBag.CostCentre_ID = new SelectList(db.CostCentres, "ID", "Name");
        ViewBag.Location_ID = new SelectList(db.Locations, "ID", "Name");
        ViewBag.User_ID = new SelectList(db.UCMUsers, "User_ID", "EmployeeNo");
        return View();
    } 
这一观点:

<div class="editor-field">
            @Html.DropDownList("User_ID", String.Empty)
            @Html.ValidationMessageFor(model => model.User_ID)
 </div>

@DropDownList(“User_ID”,String.Empty)
@Html.ValidationMessageFor(model=>model.User\u ID)

谢谢您的回答,但我要完成的是在我的视图中为我创建的@Html.DropDownListFor(在Visual Studio中自动生成-添加视图)。这可能吗?在视图中,不要忘记将模型指定为GroupPolicyViewModel。这可能会有所帮助:不幸的是,这仍然意味着我必须在视图中手动创建DropDownList for。这有什么办法吗?
   public ActionResult Create()
    {
        ViewBag.CostCentre_ID = new SelectList(db.CostCentres, "ID", "Name");
        ViewBag.Location_ID = new SelectList(db.Locations, "ID", "Name");
        ViewBag.User_ID = new SelectList(db.UCMUsers, "User_ID", "EmployeeNo");
        return View();
    } 
<div class="editor-field">
            @Html.DropDownList("User_ID", String.Empty)
            @Html.ValidationMessageFor(model => model.User_ID)
 </div>