I want to pass model to Post method of controller. When method is called it shows null value for content and 0 for Id. Ideally it should contain the values of model it has displayed.

View:
@model MvcApplication4.Models.WorldModel
@{
ViewBag.Title = "Information";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Information", "World", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<br />
@Html.DisplayFor(model => model.Id)
<br />
@Html.DisplayFor(model => model.Content)
<br />
<input type="submit" value="Next" />
}
Controller: Method called when click on submit button.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Information(WorldModel worldModel)
{
CandidateSession cs = (CandidateSession)Session["Can"];
var can = cs.Candidates.Where(x => x.IsNameDispalyed == false);
if (can.Count() > 0)
{
var can1 = can.First();
can1.IsNameDispalyed = true;
Session["Can"] = cs;
return View(new WorldModel() { Id = can1.Id, Content = can1.Name });
}
return View(new WorldModel());
}
Model:
public class WorldModel
{
public int Id { get; set; }
public string Content { get; set; }
}
You should add hidden inputs containing your values :
@Html.HiddenFor(model => model.Id)
@Html.HiddenFor(model => model.Content)
This is because the model binder will search for inputs (like textboxes, or hidden fields) to get values and associated them with your model properties (based on input names). No input is created with DisplayFor, so the model binder can't find your values when you submit your form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With