I’m having trouble submitting the fields in my View (Textboxes and Checkboxes) to my Model and am not sure how to continue. Every time i hit the button that is supposed to submit to the model, the controller checks the fields that should have been set by the view, but keeps returning false. So either they haven’t been set in the first place, or the controller is reading them wrong. Either way, I am at a loss. Please help :X
View (somewhat simplified):
@model Model
@Html.ValidationSummary()
@{ Html.BeginForm("PrintReport", "Controller", FormMethod.Get, new { @class = "form_ll" }); }
<h1>@ViewBag.Title</h1>
<div class="group">
@Html.ValidTextBoxFor(Model => Model.ToDate)
@Html.ValidTextBoxFor(Model => Model.FromDate)
@Html.CheckBoxFor(Model => Model.Geplakt)
@Html.CheckBoxFor(Model => Model.Geparafeerd)
@Html.CheckBoxFor(Model => Model.Verschreven)
@Html.CheckBoxFor(Model => Model.Geannuleerd)
@Html.CheckBoxFor(Model => Model.Vermist)
@Html.CheckBoxFor(Model => Model.Vernietigd)
@Html.CheckBoxFor(Model => Model.Onbruikbaar)
@Html.CheckBoxFor(Model => Model.Misdruk)
@Html.CheckBoxFor(Model => Model.Teruggevonden)
@Html.CheckBoxFor(Model => Model.InOnderzoek)
</div>
<div class="button">
@Html.Button("Print")
</div>
@{ Html.EndForm(); }
Model:
[Serializable]
public class Model : DomainObject
{
[DataType(DataType.Date)]
public DateTime? FromDate { get; set; }
[DataType(DataType.Date)]
public DateTime? ToDate { get; set; }
public bool Geplakt { get; set; }
public bool Geparafeerd { get; set; }
public bool Verschreven { get; set; }
public bool Geannuleerd { get; set; }
public bool Vermist { get; set; }
public bool Vernietigd { get; set; }
public bool Onbruikbaar { get; set; }
public bool Misdruk { get; set; }
public bool Teruggevonden { get; set; }
public bool InOnderzoek { get; set; }
public Model()
{
// Constructor
}
}
Controller:
public class Controller : ModelController<Model>
{
[HttpGet]
public ActionResult Index()
{
Model = new Model();
return InternalIndex();
}
[HttpGet]
public ActionResult InternalIndex()
{
return View("Index", Model);
}
[HttpGet]
public ActionResult PrintReport()
{
if (!Model.FromDate.HasValue || !Model.ToDate.HasValue)
ModelState.AddModelError("Date", "At leaste one date is null");
else {
if (Model.FromDate.Value.CompareTo(Model.ToDate.Value) >= 0)
ModelState.AddModelError("Date", "First date is later then the second one");
}
if(Model.IsAnythingChecked())
ModelState.AddModelError("Checkboxes", "You haven't checked any checkboxes");
if (ModelState.IsValid)
{
return View("PrintReport", Model);
}
else
{
return InternalIndex();
}
}
You are using GET instead of POST. You’re sending your model to the controller not receiving information. The one line should read this:
You also need to send your Model to the controller and set the method in your controller to HttpPost:
Give that a try.