0

我只是在学习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,但不显示值。请建议。

4

2 回答 2

0

您将其存储并ViewBag.StoreView,ViewBag.Stores

public ActionResult IndexDDL()
{
     ViewBag.Stores = GetStoreSelectList();
     return View();
}

@Html.DropDownList("store", ViewBag.Stores as SelectList, "Select a Store")

作为旁注,这是使用dynamic object. 我建议将属性放在 a 中ViewModel,以便获得智能感知。

于 2013-05-02T23:59:58.767 回答
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 --"
)

我希望这可以引导您朝着正确的方向前进:)

于 2013-05-03T06:08:17.480 回答