如何使用asp.net MVC SQL和EF在同一视图中创建来自不同模型的两个下拉列表
本文关键字:模型 两个 下拉列表 创建 MVC net asp 何使用 SQL 视图 EF | 更新日期: 2023-09-27 18:13:03
我正在开发一个ASP。asp.net MVC 3应用程序,使用c#和SQL Server 2005。我正在使用实体框架与代码优先的方法。
我有一个模型Profile_Ga与它视图(索引,创建,…)。
我在这个模型的索引中创建了一个下拉列表来加载id (ID_Gamme)。
我现在想加载另一个表的id(另一个模型是Poste)在Profil_Ga的索引
但是总是出现这个错误:
数据绑定:"MvcApplication2.Models。Profile_Ga'不包含属性名称为' id_post '。
是Profile_Ga的控制器:
namespace MvcApplication2.Controllers
{
public class ProfileGaController : Controller
{
private GammeContext db = new GammeContext();
//
// GET: /ProfileGa/
public ViewResult Index(Profile_Ga profile_ga, Poste poste)
{
ViewBag.ID_Gamme = new SelectList(db.Profil_Gas, "ID_Gamme", profile_ga.ID_Gamme);
ViewBag.ID_Poste = new SelectList(db.Postes, "ID_Poste", poste.ID_Poste);
return View(db.Profil_Gas.ToList());
}
,这是我在索引中添加的内容:
<%:Html.Label("Gamme :")%>
<%: Html.DropDownList("ID_Gamme", new SelectList(Model, "ID_Gamme", "ID_Gamme ")) %>
<%:Html.Label("Poste :")%>
<%: Html.DropDownList("ID_Poste", new SelectList(Model, "ID_Poste", "ID_Poste ")) %>
这个错误是正确的。模型中不包含ID_Poste
。
您正在将db.Postes
存储到ViewBag中,但传递给视图的模型只是db.Profil_Gas
,如本部分所示:return View(db.Profil_Gas.ToList());
-这将不包含db.Postes
。
当您想要显示两个独立的东西时,最好的方法是创建一个新的ViewModel类,其中包含像这样的两个东西。
public class MyViewModel
{
// The two drop-down lists
public List<Profile_Ga> Profile_Gas { get; set; }
public List<Poste> Postes { get; set; }
// Used to store selected items
public int SelectedProfile_Ga { get; set; }
public int SelectedPoste { get; set; }
}
然后在Controller
[HttpGet]
public ActionResult Index(Profile_Ga profile_ga, Poste poste)
{
var viewModel = new MyViewModel();
viewModel.Profile_Gas = db.Profil_Gas.ToList();
viewModel.Postes = db.Postes.ToList();
return View(viewModel);
}
[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
string debug = string.Format("You selected Profile: {0} and Poste: {1}", viewModel.SelectedProfile_Ga, viewModel.SelectedPoste);
return View(viewModel);
}
最后在您的视图
<%: Html.DropDownList("SelectedProfile_Ga", new SelectList(Model.Profile_Gas, "ID_Gamme", "NameToShow")) %>
<%: Html.DropDownList("SelectedPoste", new SelectList(Model.Postes, "ID_Poste", "NameToShow")) %>
然后您只需将NameToShow
替换为您想在下拉框中显示的属性。然后,当您提交表单时,ViewModel将与下拉框的值一起传递回来(如代码示例所示)。在HttpPost
项目的调试中放置断点以检查值是否正确,然后您应该可以很好地运行!
你的视图模型是Profile_Gas
所以你不能做
<%:Html.Label("Poste :")%>
<%: Html.DropDownList("ID_Poste", new SelectList(Model, "ID_Poste", "ID_Poste ")) %>
您需要创建一个视图模型来封装Profile_Ga
和Poste
public class ViewModel
{
public List<Poste> Postes { get; set; }
public List<Profile_Ga> Profile_Gas { get; set; }
}
并从控制器返回这个视图模型
public ViewResult Index(Profile_Ga profile_ga, Poste poste)
{
return new ViewModel
{
Postes = db.Postes.ToList(),
Profile_Gas = db.Profil_Gas.ToList();
}
}
你的视图看起来就像
<%:Html.Label("Gamme :")%>
<%: Html.DropDownList("ID_Gamme", new SelectList(Model.Profile_Gas, "ID_Gamme", "ID_Gamme ")) %>
<%:Html.Label("Poste :")%>
<%: Html.DropDownList("ID_Poste", new SelectList(Model.Postes, "ID_Poste", "ID_Poste ")) %>