如何使用实体框架将dropdownlist绑定到类型<model>的列表

时间:2018-07-31 15:49:58

标签: asp.net-mvc entity-framework razor

我已经举了很多例子,但我想我找不到想要的东西。

我有一个包含类的模型:

public class StateResources
{
  public List<States> statesList { get; set;}
}

public partial class States
{
    public int? StateID { get; set; }
    public string StateName { get; set; }
}

我有一些可执行的代码,可从填充statesList的数据库中获取数据。我在控制器中调用它,以便可以在视图中显示它。

public ActionResult StatesView(List<States> listofStates)
{
  if(ModelState.IsValid)
  {
     try
     {
         StatesResources stateResource = new StatesResources();
         stateResource.ReturnStateResources(); // Assume there is a method in 
                                               // my States Resource Class 
                                               // that executes code to 
                                               // retrieve data from a db.
                                               // and turns it into a list.

         listOfStates = stateResource.statesList;
         return(listOfStates);
     }
     catch (Exception ex)
     {
        // catches exception if exists
     }
  }
  else
  {
    //throws error if ModelState.IsValid == false.
  }

     return View("StatesView");
}

我认为:

@model List<States>

   <body>
     @Html.DropDownListFor(m => m.StateID) @*This is where I'm having trouble*@
   </body>

我不知道如何将模型添加到该下拉列表中。我认为问题出在必须是选择列表项的位置,但是我不太确定,因为我从一些示例中看到过DDL不使用它们。我知道有几个关于如何将数据传递到DDL的示例,但是我认为我没有遇到类似于我的示例的关于如何从db中检索数据并使其成为特定类类型的列表的例子。

3 个答案:

答案 0 :(得分:1)

我对您的控制器代码很困惑,因为它看起来像POST和GET,因为您正在将列表传递给控制器​​操作方法,并且您收到了ModelState.IsValid调用。

您无需将自定义类型返回到视图。最简单的方法是直接从数据提供者中填充SelectListItem。

ViewModel

public class StatesEditViewModel
{
    [Required]
    public int SelectedState { get; set; }
    public IEnumerable<SelectListItem> States { get; set; }
}

控制器动作

    [HttpGet]
    public ActionResult StatesEdit()
    {
        StatesResources stateResource = new StatesResources();
        stateResource.ReturnStateResources(); // Assume there is a method in 
                                              // my States Resource Class 
                                              // that executes code to 
                                              // retrieve data from a db.
                                              // and turns it into a list.

        var model = new StatesEditViewModel { States = stateResource.statesList.Select(s => new SelectListItem { Text = s.StateName, Value = s.StateID }).ToList() };

        return View(model);
    }

    [HttpPost]
    public ActionResult StatesEdit(StatesEditViewModel editModel)
    {
        if (!ModelState.IsValid)
        {
            //repopulate your state list
            StatesResources stateResource = new StatesResources();
            stateResource.ReturnStateResources(); // Assume there is a method in 
                                                  // my States Resource Class 
                                                  // that executes code to 
                                                  // retrieve data from a db.
                                                  // and turns it into a list.

            var model = new StatesEditViewModel { States = stateResource.statesList.Select(s => new SelectListItem { Text = s.StateName, Value = s.StateID }).ToList() };
            return View(model);
        }

        //Save your selected sate to somewhere
        //redirect back to your GET action
        return RedirectToAction("StatesEdit");
    }

最后是您的看法

@model StatesEditViewModel

@{
    ViewBag.Title = "title";
    Layout = "_Layout";
}

<h2>title</h2>
@using (Html.BeginForm("StatesEdit", "<controller where you define you actions>", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.DropDownListFor(model => model.SelectedState, Model.States)
}

答案 1 :(得分:0)

是的,您可以将DropDownListFor与Model绑定。使用这个:

@Html.DropDownListFor(m => m.StateID, new SelectList(Model.statesList ,"StateID", "StateName"))

public class StateResources
    {
        public List<States> statesList { get; set; }
        public int StateId { get; set; }
    }

您认为:

@model StateResources

在您的控制器中:

public ActionResult StatesView(StateResources model)
{
  if(ModelState.IsValid)
  {
     try
     {
         StatesResources stateResource = new StatesResources();
         stateResource.ReturnStateResources(); // Assume there is a method in 
                                               // my States Resource Class 
                                               // that executes code to 
                                               // retrieve data from a db.
                                               // and turns it into a list.

         model.statesList = stateResource.statesList;         
     }
     catch (Exception ex)
     {
        // catches exception if exists
     }
  }
  else
  {
    //throws error if ModelState.IsValid == false.
  }

     return View("StatesView", model);
}

答案 2 :(得分:0)

在视图中

<%=Html.DropDownList("TypeDropDown", Model.TypeSelectList, new { onclick = "Type_OnChange()" })%>

在视图模型中。

public SelectList TypeSelectList;

public void loaddata
{
 TypeSelectList = GetOptions();
}