C# 将两个模型传递给一个视图的问题
我想使用ViewModel将两个模型传递给一个视图 我的模型:C# 将两个模型传递给一个视图的问题,c#,linq,entity-framework,asp.net-mvc-4,razor,C#,Linq,Entity Framework,Asp.net Mvc 4,Razor,我想使用ViewModel将两个模型传递给一个视图 我的模型: public class Candidat { public int Id { set; get; } public string num_cin { set; get; } public ICollection<Poste> postes { get; set; } } public class Poste { publi
public class Candidat
{
public int Id { set; get; }
public string num_cin { set; get; }
public ICollection<Poste> postes { get; set; }
}
public class Poste
{
public int Id { set; get; }
public string poste_name {set;get}
public List<Candidat> candidats {set;get;}
}
public class PosteCandidatViewModel
{
public Candidat candidat { get; set; }
public Poste poste { get; set; }
}
观点:
@model ProcRec.Models.PosteCandidatViewModel
<td>@Html.TextBoxFor(model => model.candidat.num_cin)</td>
<td><p>@Html.DropDownListFor(model => model.poste.Id,new
SelectList(ViewBag.Postes, "Id", "intitule_poste"),"choisir le poste")
</p></td>
@model-ProcRec.Models.PosteCandidatViewModel
@Html.TextBoxFor(model=>model.candidate.num\u)
@DropDownListFor(model=>model.poste.Id,新
选择列表(ViewBag.Postes、“Id”、“intitule_poste”)、“choisir le poste”)
我的问题是linq查询没有给出我想要的结果
(但如果我给num_cina一个poste.id一些值,那就是工作)
所以问题是num_cin没有dropdownlist中的值…这就像有一个空值 更改POST方法签名以接受模型,并访问模型属性
[HttpPost]
public ActionResult Index(PosteCandidatViewModel model)
{
Poste poste = model.Poste;
string num_cin = model.Candidat.num_cin;
参数字符串num\u cin
为空的原因是@TextBoxFor(model=>model.candidate.num\u cin)
生成了
,它试图映射到包含属性num\u cin
的属性candidate
。或者,upi可以使用
[HttpPost]
public ActionResult Index( Poste poste, [Bind(Prefix="candidat")]string num_cin)
{
注意,如果ModelState
无效,则需要重新分配在DropDownListFor()中使用的ViewBag.Postes
的值
我试着让它给我一个异常…………值不能为空。参数名称:items(drownlist)异常发生在哪里?我修复了异常,这是因为我在模型中进行了验证……我不想将PosteCandidatViewModel作为我的Post操作的参数传递……因为如果我这样做,它会给我一些验证错误(因为我的模型包含很多必需的属性)你的表单在你的.cshtml
视图文件中的什么位置?看起来好像不工作!!:(num\u cin仍然有null!!!!!我讨厌这种问题
[HttpPost]
public ActionResult Index( Poste poste, [Bind(Prefix="candidat")]string num_cin)
{
if (ModelState.IsValid)
{
....
}
ViewBag.Postes = // set the value here before returning the view
return View(model);