2016-10-26 281 views
0

名稱和ID存儲在數據庫中。我想從數據庫顯示所有名稱和ID到ViewPage下拉菜單。在這裏,我只在下拉列表中顯示名稱列。是否有可能在單個下拉列表中顯示兩列?請讓我知道解決方案。在Razor下拉列表中顯示兩列值?或Html下拉列表?

控制器:

var Employe = (from table in dc.tbl_EmployeeDetails 
       select table.Employee_Name).ToList(); 
ViewData["empName"] = Employe ; 

var department = (from table in dc.tbl_EmployeeDetails 
        select table.Department).ToList(); 
ViewData["dept"] = department; 

查看

<select id="reportto" disabled="disabled" font-size:14px"> 
    @foreach(var person in ViewData["empName"] as List<string>) 
    { 
     if(@[email protected]) 
     { 
      <option>@person</option> 
     } 
    } 
</select> 

這裏我只是在下拉列表中顯示的名稱。如何在單個下拉菜單中顯示姓名和部門?

回答

0

ViewBag.EmployeeDetails= db.EmployeeDetails.ToList();

在視圖

@model ... 
 
@{ 
 
     ViewBag.Title ="Employe "; 
 
     List<Proyect.Models.EmployeeDetails> Details = ViewBag.EmployeeDetails; 
 
} 
 

 
<select name="EmployeeDetails" class="form-control" id="EmployeeDetails"> 
 
      <option>Select one</option> 
 
      @foreach (var Detail in Details) 
 
      { 
 
      <option id="@Docs.Id_Employee_Detail" value="@Docs.Id_Employee_Detail">@Detail.Name : @Detail.Department</option> 
 
      } 
 
</select>

並且收到參數中的控制LER

public ActionResult Something(int EmployeeDetails) 
 
{ 
 
var EmployeeDetailSelected = dc.tbl_EmployeeDetails.Find(EmployeeDetails); 
 
}

1

請做一件事。

請使用SelectListItem作爲綁定下拉列表。

List<SelectListItem> lstLocation = new List<SelectListItem>(); 

SqlParameter[] parameters = { new SqlParameter("@ID", ID),new 
SqlParameter("@Name",Name)}; 

DataSet dsLocation = SqlHelper.ExecuteDataset(CommandType.StoredProcedure, "GetPersonalInfo", parameters); 

    if (dsLocation != null && dsLocation.Tables.Count > 0 && dsLocation.Tables[0].Rows.Count > 0) 
      { 
       lstLocation = (from drLocation in dsLocation.Tables[0].AsEnumerable() 
           select new SelectListItem { Text = `drLocation["PersonID"].ToString() + ' - '+ drLocation["PersonName"].ToString(), Value = drLocation["PersonID"].ToString() }).ToList();` 
      } 

並存儲此列表obejct查看包並將其設置爲Dropdownlist中的視圖。使用上述代碼

ViewBag.Location=lstLocation ; 

@Html.DropDownList("Location", ViewBag.Location as List<SelectListItem>, 
"-SELECT-", new { data_val = "true", data_val_required = "Please select 
location", @class = "form-control" }) 

,你的數據就會像 '1-ROnak', '2-和Manish' 在下拉列表中。 選擇後,您可以使用' - '拆分名稱和ID。

謝謝。

在控制器