user3479388
user3479388

Reputation: 9

MVC validation with only HTML

I am working on a contact us form and I was able to do a successful validation but i have a small problem,

when I submit and miss one of the required values, the form comes back with the error message and does not keep the value and I have noticed that only happens if I use HTML only, it will work fine with HTML helpers.

Here is a snippet of my code:

<div class="form-group">
                        @Html.LabelFor(model => model.FirstName, "First Name")
                        <div>
                            <input class="form-control" name="FirstName" id="FirstName" data-val="true" type="text" value="" />
                            @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                        </div>
                    </div>

But it will work for the last name field:

<div class="form-group">
                        @Html.LabelFor(model => model.LastName, "Last Name")
                        <div>
                            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                        </div>
                    </div>

Filling the info: filling the info

Notice after submitting the last name stays there but the first name disappears: notice after submitting the last name stay there but the first name disappear

Any help will be appreciated :)

Upvotes: 0

Views: 91

Answers (1)

Shyju
Shyju

Reputation: 218942

Because your input tag's value property value is set to an empty string.

You should use the Html.TextBoxFor helper method to generate the inuput field and it will show you the value you posted when your model validation fails. The helper method will also generate the relevant html5 attribute needed for client side unobtrusive validation.

@model ContactViewModel 
@using(Html.BeginForm())
{
   @Html.TextBoxFor(s=>s.FirstName)
   @Html.ValidationMessageFor(model => model.FirstName)
   <!-- Other fields -->
   <input type="submit" />               
}

Assumin your HttpPost action method is returning the posted model back to the view which Model validation fails

[HttpPost]
public ActionResult Contact(ContactViewModel model)
{
  if(ModelState.IsValid)
  {
     // to do : return something
  }
  return View(model);
}

Upvotes: 1

Related Questions