Jared Stark
Jared Stark

Reputation: 31

Data Annotations not including data- attributes on form elements

I must be missing something totally obvious here. I just started with a clean project - MVC 3/Razor - and I'm attempting to configure unobtrusive JavaScript validation. Everything I can find says I just need to add the data annotations to my model, and set UnobtrusiveJavaScriptEnabled to true in the web.config, and everything should work. The problem I'm having is that when I look and the rendered source, my input field doesn't even have the data-val property. Here's what I've got:

public class PersonModel
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }
}

And in the controller:

    public ActionResult Index()
    {
        return View(new Models.PersonModel());
    }

And in the View:

@model ValidationTest.Models.PersonModel
...
@Html.EditorFor(m => m.FirstName)

I would expect to see an input tag rendered that includes the data-val attribute, but instead I'm only seeing:

<input class="text-box single-line" id="FirstName" name="FirstName" type="text" value="">

Am I missing a simple setting somewhere?

Upvotes: 0

Views: 985

Answers (1)

nemesv
nemesv

Reputation: 139758

According to the implemetation:
Only render attributes if unobtrusive client-side validation is enabled, and then only if we've never rendered validation for a field with this name in this form. Also, if there's no form context, then we can't render the attributes (we'd have no to attach them to).

So I guess you need to put your EditorFor inside a Form

@using (Html.BeginForm())
{
    @Html.EditorFor(m => m.FirstName)
}

Upvotes: 4

Related Questions