我想使用ViewModel
将两个模型传递到一个视图我的模特:
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; }
}
控制器动作:
[HttpPost]
public ActionResult Index( Poste poste,string num_cin)
{
if (ModelState.IsValid)
{
var v = (from c in _db.Candidats
where c.num_cin == num_cin
&& c.postes.Any(p => p.Id == poste.Id)
select c)
.SingleOrDefault();
if (v != null)
{
return RedirectToAction("Inscription", "Candidat");
}
else
{
return RedirectToAction("index", "BureauOrdre");
}
}
return View();
观点:
@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>
我的问题是linq查询没有给出我想要的结果 (但如果我给了num_cin一个poste.id一些值,那就是它的工作)
所以问题是num_cin没有来自下拉列表的值...就像有一个空值!!!!!!!!!
答案 0 :(得分:0)
更改POST方法签名以接受模型,并访问模型属性
[HttpPost]
public ActionResult Index(PosteCandidatViewModel model)
{
Poste poste = model.Poste;
string num_cin = model.Candidat.num_cin;
参数string num_cin
为空的原因是@TextBoxFor(model => model.candidat.num_cin)
生成<input type="text" name="candidat.num_cin" ... />
,它正在尝试映射到包含属性candidat
的属性num_cin
。或者upi可以使用
[HttpPost]
public ActionResult Index( Poste poste, [Bind(Prefix="candidat")]string num_cin)
{
注意,如果ModelState
无效,则需要重新分配您在ViewBag.Postes
DropDownListFor()
的值
if (ModelState.IsValid)
{
....
}
ViewBag.Postes = // set the value here before returning the view
return View(model);