oumaima oumaima - 8 months ago 35
ASP.NET (C#) Question

Passing Data from View to Controller failed in asp.net mvc

I want to pass data from view to controller but it always returns 0 and I don't know why.
I have to verify if the entred code is the same as passed in parametre of ActionResult Sortie() but I can't get the value entred in view.

View:

@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>


Controller:

//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");
}

}


Help please and thank you.

Answer Source

Do not access the Request.Form directly. Instead, your POST action should accept the ViewModel as parameter.

[HttpPost]
public ActionResult Sortie(ViewModel.DemandeViewModel postData) {
     int c = postData.CodeBarre; // assuming CodeBarre is an int in the ViewModel
     if ((int)TempData["codebarre"] == c) {
         // ...
     }
     // ...
}

Also in your View, let MVC set the name attribute so the ViewModel can be bound correctly by the ModelBinder.

@Html.EditorFor(model => model.CodeBarre, new { htmlAttributes = new { @class = "form-control" } })

Because you have an Editor input for the CodeBarre, you do not need another hidden input for it. Remove the line

@Html.HiddenFor(model => model.CodeBarre)