MVC dropdownlist
本文关键字:dropdownlist MVC | 更新日期: 2023-09-27 18:04:54
如何填充@HTML。下拉列表或@HTML。下拉列表从SQL Server数据库使用linq和MVC模型在c# ?我见过很多使用ViewData的例子,但我想使用模型。我认为我的挂起是从数据库中获取数据,并进入一个可以在视图中使用的列表。
我需要一个简单而详细的例子。
谢谢!
我试着给你做一个有三种样式的样品
视图<%= 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; }
}
注意:当你创建你的视图
我没有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)