[英]populate @html.listboxfor using stored procedure
我首先在mvc4(razor)中使用帶有db的實體
要求 :我有sp返回id和顯示名稱,我需要在@html.listbox中顯示名稱,我使用接口從存儲過程中獲取詳細信息。當我從存儲過程中獲得控制器中的結果時,我得到了保存結果到列表框,我無法弄清楚如何將它存儲在列表框中。 我對控制器代碼感到震驚。請幫助。
碼:
public class projService :Iproj
{
project dbContext;
public projService()
{
dbContext = new projectEntities();
}
public List<GetResourceOrderDisplay_Result> Getresorderdisplay()
{
List<GetResourceOrderDisplay_Result> oGetresorderdisplay = new List<GetResourceOrderDisplay_Result>();
oGetresorderdisplay = dbContext.GetResourceOrderDisplay().ToList();
return oGetresorderdisplay.ToList();
}
}
控制器:
public ActionResult testview()
{
List<GetResourceOrderDisplay_Result> listboxdata = new List<GetResourceOrderDisplay_Result>();
listboxdata = _Scheduler.Getresorderdisplay();
ListboxViewModel objListboxViewModel = new ListboxViewModel();
//struck with the follwing line.
objListboxViewModel.resourcename=listboxdata ????
return View(objListboxViewModel);
}
視圖:
@model project.ViewModels.ListboxViewModel
@Html.ListBoxFor( m=> m.resourcename,Model.resourcename, new { @class = "resList",style="height: 462px;"})
模型:
public class ListboxViewModel
{
public string resourceid{get; set; }
//listbox Values
public List<SelectListItem> resourcename{get; set;}
}
編輯:GetResourceOrderDisplay_Result
using System;
using System.Collections.Generic;
namespace proj.Data
{
public partial class GetResourceOrderDisplay_Result
{
public int ID { get; set; }
public string DisplayName { get; set; }
}
}
Edit2:這是我在更新后得到的錯誤:
**Edit 3:**
基本上,您需要做的是將從數據庫中檢索到的List<SelectListItem>
數據轉換為List<SelectListItem>
以便顯示它。 Linq
Select
方法使這很簡單:
objListboxViewModel.resourcename =
listboxdata.Select(x => new SelectListItem() { Text = x.DisplayName,
Value = x.ID.ToString() })
.ToList();
因此,將Text
和Value
屬性設置為將取決於GetResourceOrderDisplay_Result
的定義以及它具有的屬性。 在Select
方法中, x
表示listboxdata
列表的單個元素,類型為GetResourceOrderDisplay_Result
,因此您可以訪問它的屬性,如x.Property
。 以這種方式構造的Select
方法將返回一個新的SelectListItem
列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.