2013-08-16 49 views
1

我有一個頁面,用於在我的Database.One字段中的某個表中插入新行,它是來自同一個表中的父項的外鍵。所以我需要一個drobdownlist供用戶選擇父項。 這是我的表定義:在Razor引擎中創建DropDownList MVC

Id   Integer 
ParentId_Fk Integer 
Body  Varchar 
Title  Varchar 

創建頁面查看:

@model MVCDrLaptop.Models.Education 

@{ 
    Layout = null; 
} 

<!DOCTYPE html> 

<html> 
<head> 
    <title>Create</title> 
</head> 
<body> 
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

    @using (Html.BeginForm()) { 
     @Html.ValidationSummary(true) 
     <fieldset> 
      <legend>Education</legend> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.Title) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.Title) 
       @Html.ValidationMessageFor(model => model.Title) 
      </div> 

      <div class="editor-label"> 
       @Html.LabelFor(model => model.Text) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(model => model.Text) 
       @Html.ValidationMessageFor(model => model.Text) 
      </div> 

      <div class="editor-field"> 
       //here is for parentId_FK DropDownList 
      </div> 

      <p> 
       <input type="submit" value="Create" /> 
      </p> 
     </fieldset> 
    } 

    <div> 
     @Html.ActionLink("Back to List", "Index") 
    </div> 
</body> 
</html> 

所以我應該寫什麼,用於創建我的DropDownList?

+1

訪問http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and- jquery/using-the-dropdownlist-helper-with-aspnet-mvc – Satpal

回答

3

首先從數據庫中獲取所有值的一個例子。

控制器:

IEnumerable<SelectListItem> items = from value in values 
             select new SelectListItem 
             { 
              Text = value.ToString(), 
              Value = value.ToString(), 
              Selected = value == selectedMovie, 
             }; 
    ViewBag.MovieType = items; 

查看:

@Html.DropDownList("items") 
+0

謝謝,你的解決方案是正確的:) –

+0

謝謝,最受歡迎 –