adam78
adam78

Reputation: 10068

Add Validation Message To View

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> 

Upvotes: 0

Views: 1607

Answers (1)

BinaryBoss
BinaryBoss

Reputation: 64

I would go with html helpers.

@Html.ValidationMessage("Address") 

This will automatically generate the HTML:

<span class="field-validation-valid" data-valmsg-for="address" data-valmsg-replace="true"></span>`

Your code looks correct.

if (string.IsNullOrEmpty(collection["Address"]))
{
  // Set the field validation error span message
  ModelState.AddModelError("Address", "This field is required.");
 return View();
}

Upvotes: 1

Related Questions