[英]Passing Data from View to Controller failed in asp.net mvc
我想將數據從視圖傳遞到控制器,但它始終返回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) {
// ...
}
// ...
}
同樣在您的View中,讓MVC設置name
屬性,以便ModelBinder可以正確綁定ViewModel。
@Html.EditorFor(model => model.CodeBarre, new { htmlAttributes = new { @class = "form-control" } })
因為您有CodeBarre的Editor輸入,所以不需要其他隱藏輸入。 刪除線
@Html.HiddenFor(model => model.CodeBarre)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.