-1

如何使用 C# 中的 linq 和 MVC 模型从 SQL Server 数据库中填充 @HTML.dropdownlist 或 @HTML.dropdownlistfor?我看过很多使用 ViewData 的示例,但我想使用模型。我认为我的挂断是从数据库中获取数据并放入可以在视图中使用的列表中。

我需要一个简单而详细的例子。

谢谢!

4

2 回答 2

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;

模型

public class YourModel
{
    public IEnumerable<YourEntity> YourSource{ get; set; }
}

注意:当您创建视图时,您必须在视图中注入您的模型

于 2013-03-19T14:32:03.320 回答
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;
        }
    }
}

索引.cshtml:

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

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@Html.RFSSelect("DropDownId", Model.DropDownData)
于 2013-03-19T14:37:26.380 回答