2013-03-19 99 views
-1

如何在C#中使用linq和MVC模型從SQL Server數據庫填充@ HTML.dropdownlist或@ HTML.dropdownlistfor?我見過很多使用ViewData的例子,但我想使用模型。我覺得我掛斷從數據庫到可以在視圖中使用的列表獲取數據。MVC下拉列表

一個簡單而具體的例子就是我所需要的。

謝謝!

+0

取決於您是否使用EF或oledb呼叫? – 2013-03-19 14:23:21

回答

0

我試圖讓你用三個演員模式的

查看

<%= Html.DropDownList("YourControl", Model.YourSource)%> 

控制器

IEnumerable<YourEntity> result = 
          from item in GetListSample() 
          select new YourEntity 
          { 
           Text = item.Name, 
           Value = item.Value 
          }; 
    model.YourSource= result; 

型號

注意一個樣本:必須注入你模型在視圖中,當您創建視圖

0

我沒有爲SQL的例子,但我可以幫你呈現一個頁面,MVC

控制器:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace TestPortal.Areas.JB.Controllers 
{ 
    public class ExampleController : Controller 
    { 
     // 
     // GET: /JB/Example/ 

     public ActionResult Index() 
     { 
      Models.Example.ExampleIndex output = new Models.Example.ExampleIndex(); 
      output.DropDownData.Add(new SelectListItem() 
      { 
       Text = "One", 
       Value = "1" 
      }); 

      output.DropDownData.Add(new SelectListItem() 
      { 
       Text = "Two", 
       Value = "2" 
      }); 


      return View(output); 
     } 

    } 
} 

ExampleIndex.cs:注意這是一件好事,以建立一個視圖模型將數據傳遞給視圖

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace TestPortal.Areas.JB.Models.Example 
{ 
    public class ExampleIndex 
    { 
     public ExampleIndex() 
     { 
      this.DropDownData = new List<SelectListItem>(); 
     } 

     public List<SelectListItem> DropDownData 
     { 
      get; 
      set; 
     } 
    } 
} 

Index.cshtml:

@model TestPortal.Areas.JB.Models.Example.ExampleIndex 

@{ 
    ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 


@Html.RFSSelect("DropDownId", Model.DropDownData)