Question

I have my cshtlm page with the next code:

@using (Html.BeginForm("Optional", "ConfigurationSilo2", FormMethod.Post, new { id = "storeDataForm" }))
{          
     @Html.TextBoxFor(x => x.Height)  

    <div align="right">
        <input type="submit" id="Avanti" value="@ViewRes.ConfigurationString.buttonNext" name="@ViewRes.ConfigurationString.buttonNext" />
    </div>
}

My html generated code is:

<form action="/ConfigurationSilo2/Optional" id="storeDataForm" method="post">

     <input data-val="true" data-val-number="The field Height must be a number." data-val-required="The Height field is required." id="Height" name="Height" type="text" value="0" />          
    <div align="right">
        <input type="submit" id="Avanti" value="Next" name="Next" />
    </div>
</form>

This is my model code class:

public class Spondina
{
    public int Height { get; set; }
    public int Quantity { get; set; }
    public float UnitPrice { get; set; }
    public float TotalCost { get; set; }
}

why are there tags data-val data-val-number data-val-required in my input tag?

Was it helpful?

Solution

That's the MVC validation kicking in. Do you have data annotations on your model? I'm guessing that the Height property has [Required] against it? The attributes are used by the unobtrusive client validation framework. Here is the line within the input helper that adds those tags:

tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata));

The HtmlHelper has a ClientValidationRuleFactory, which is initialized in the constructor of HtmlHelper with, amongst other things, a ClientDataTypeModelValidatorProvider, which examines the metadata of your model and applies appropriate validation rules in cases of numeric types in your model, for example. If you have client validation enabled and numeric types in your model, e.g. Height as an int, the helpers will inject unobtrusive client validation into those inputs during render.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top