我想将数据从视图传递给控制器,但它总是返回 0,我不知道为什么。我必须验证输入的代码是否与传入的 ActionResult Sortie() 参数相同,但我无法在视图中获取输入的值。
看法:
@model ViewModel.DemandeViewModel
@{
ViewBag.Title = "Sortie";
}
<div class="col-xs-12">
<div class="box">
<h2>Sortie Gabarit</h2>
@using (Html.BeginForm("Sortie", "Demandes", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.CodeBarre)
@ViewBag.error
@Html.ValidationMessage("error_msg")
<div class="form-group">
@Html.LabelFor(model => model.CodeBarre, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CodeBarre, new { htmlAttributes = new { @class = "form-control", @name = "codeB" } })
@Html.ValidationMessageFor(model => model.CodeBarre, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Sortie" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
</div>
控制器:
//Get Sortie
public ActionResult Sortie(Int64 id)
{
TempData["codebarre"] = id;
return View();
}
//Post Sortie
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Sortie()
{
var mvtrepository = new MvtRepository(db);
var c = Request.Form["codeB"];
if (Convert.ToInt64(TempData["codebarre"]) == Convert.ToInt64(c))
{
var mvtInsert = mvtrepository.InsertMvt(DateTime.Now, Convert.ToInt64(TempData["codebarre"]), 2);
return RedirectToAction("Traitement");
}
else
{
return View("Error");
}
}
请帮助,谢谢。
不要Request.Form
直接访问。相反,您的 POST 操作应该接受 ViewModel 作为参数。
[HttpPost]
public ActionResult Sortie(ViewModel.DemandeViewModel postData) {
int c = postData.CodeBarre; // assuming CodeBarre is an int in the ViewModel
if ((int)TempData["codebarre"] == c) {
// ...
}
// ...
}
同样在您的视图中,让 MVC 设置name
属性,以便 ModelBinder 可以正确绑定 ViewModel。
@Html.EditorFor(model => model.CodeBarre, new { htmlAttributes = new { @class = "form-control" } })
因为您有 CodeBarre 的编辑器输入,所以您不需要其他隐藏输入。删除该行
@Html.HiddenFor(model => model.CodeBarre)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句