我刚刚学习MVC。这是我到目前为止所尝试的内容:
public class StoreXml
{
public string StoreCode { get; set; }
public static IQueryable<StoreXml> GetStores()
{
return new List<StoreXml>
{
new StoreXml { StoreCode = "0991"},
new StoreXml { StoreCode = "0015"},
new StoreXml { StoreCode = "0018"}
}.AsQueryable();
}
在控制器中:
public SelectList GetStoreSelectList()
{
var Store = StoreXml.GetStores();
return new SelectList(Store.ToArray(),"StoreCode");
}
public ActionResult IndexDDL()
{
ViewBag.Store = GetStoreSelectList();
return View();
}
在视图中:
@Html.DropDownList("store", ViewBag.Stores as SelectList, "Select a Store")
我在这里做错了什么?下拉列表仅显示Cie_Mvc.Models.StoreXml但没有值。请建议。
答案 0 :(得分:0)
您将其存储在ViewBag.Store
并在View
,ViewBag.Stores
public ActionResult IndexDDL()
{
ViewBag.Stores = GetStoreSelectList();
return View();
}
@Html.DropDownList("store", ViewBag.Stores as SelectList, "Select a Store")
作为旁注,这是使用dynamic
object
的问题。我建议将该属性放在ViewModel
中,这样就可以获得智能感知。
答案 1 :(得分:0)
我会以不同的方式做到这一点。我会将我的班级与我的班级列表分开,如:
public class StoreXml
{
public string StoreCode { get; set; }
}
然后我会使用像存储库这样的东西来获取一些数据,即使它是硬编码的,或者你可以只从控制器中填充一个列表。始终使用视图模型在视图上表示您的数据:
public class MyViewModel
{
public string StoreXmlCode { get; set; }
public IEnumerable<StoreXml> Stores { get; set; }
}
然后你的控制器看起来像这样:
public class MyController
{
public ActionResult MyActionMethod()
{
MyViewModel viewModel = new MyViewModel();
viewModel.Stores = GetStores();
return View(viewModel);
}
private List<StoreXml> GetStores()
{
List<StoreXml> stores = new List<StoreXml>();
stores.Add(new StoreXml { StoreCode = "0991"});
stores.Add(new StoreXml { StoreCode = "0015"});
stores.Add(new StoreXml { StoreCode = "0018"});
return stores;
}
}
然后你的观点看起来像这样:
@model MyProject.ViewModels.Stores.MyViewModel
@Html.DropDownListFor(
x => x.StoreXmlCode,
new SelectList(Model.Stores, "StoreCode", "StoreCode", Model.StoreXmlCode),
"-- Select --"
)
我希望这可以引导你朝着正确的方向前进:)