Lets say I have a form with no model binding or data annotations. When the form is posted how can I return the view with a validation message beneath the control - Note I'm trying to do server side validation here?
Below is a kind of example.
<input name="Address" type="text" value="">
<span class="field-validation-valid" data-valmsg-for="Address" data-valmsg-replace="true"></span>
public ActionResult Create(FormCollection collection)
{
if (string.IsNullOrEmpty(collection["Address"])
{
// Set the field validation error span message
ModelState.AddModelError("Address", "This field is required.");
return View();
}
}
Note: I know how add validation using a view model and data annotations. In this scenario I'm unable to use a view model so need some way to manually validate and return the validation messages back to the view.
The above doesn't seem to work
* Update *
Perhaps using viewData as follows:
<span class="field-validation-valid" data-valmsg-for="Address" data-valmsg-replace="true">@ViewData["Address"]</span>
@Html.ValidationMessageFor(m => m.Address, "")beneath the control? This should display all model state errors added in your controller for that property. Also there is@Html.ValidationSummary()which displays all model state errors.return View(collection)[Required]data attribute above your Address property in your model and let the asp.net engine handle this type of validation for you.ViewBagor whatever, then iterate through that in the View. But without a model all of the seems off. How will you display the values back on the form when it fails validation? It would be a blank form with just validation errors and the user would have to fill out all the fields again.