任何人都可以告诉我如何编写Controller for C#(public ActionResult DropList()
)for Drop Down List生成Linq我希望将此SELECT DISTINCT CouName FROM Locations;
转换为Linq,以便我的下拉列表动态生成。
Chtml页面如何在@Html.DropDownListFor("")
中书写
Models.Location
答案 0 :(得分:1)
此代码将从IQueryable GetAll()方法生成一个选择列表,或者您可以直接使用from c in _context.Set<Location>()
public SelectList GetAsSelectList()
{
var locs = from c in GetAll()
select new
{
Id = c.Id,
Name = c.Name
};
return new SelectList(locs, "Id", "Name");
}
其中Id是值字段,Name是选择列表选项的文本字段。
这将分配给模型属性:
var model = new MyModel
{
LocationList = GetAsSelectList();
}
您可以将模型传递给View,并使用DropDownListFor:
@Html.DropDownListFor(x => x.MyModel.Location, Model.LocationList)
您的模型还有一个Location
属性,如果您想这样做,您可以将其设置为显示默认值。
答案 1 :(得分:1)
假设您的模型名为MyModel
控制器
public ActionResult Edit()
{
var couriers = // get your couriers from the database using your query
// Is better to assign this to a property in your view model, but ViewBag will do for now
ViewBag.CourierList = new SelectList(couriers);
var model = new YourModel();
}
查看
@model YourModel
@using(Html.BeginForm())
{
@Html.DropDownListFor(m => m.CouriersName, (SelectList)ViewBag.CourierList)
}
答案 2 :(得分:1)
据我所知,你可以这样做:
public ActionResult DropList()
{
List<SelectListItem> objResult = new List<SelectListItem>();
var result = dbContext.Locations.Select(x=>x.CouName).Distinct().ToList();
foreach(var item in result)
{
SelectListItem temp = new SelectListItem();
temp.Text = item;
temp.Value = item;
objResult.Add(temp);
}
ViewBag.DropdownResult = objResult;
return View();
}
下拉视图:
@Html.DropDownListFor(m=>m.ModelLocations, ViewBag.DropdownResult as List<SelectListItem>)
请根据需要修改代码。
答案 3 :(得分:0)
using System.Web.Mvc;
...
public static List<SelectListItem> GetItemsForDisplay(string listName)
{
//your data access function should return a list of objects
return DAL.Table.SelectByName(listName)
.Select(x=> new SelectListItem{Text=x.DisplayName, Value=x.ID})
.ToList<SelectListItem>();
}