I am having a very weird problem
I have a viewModel:
public class ServiceView
{
[Required]
[Display(Name = "Titre de l' annonce")]
public string NomService { get; set; }
[Required]
[Display(Name = "Description")]
public string DescriptionService { get; set; }
[Display(Name = "Adresse")]
public string AdresseService { get; set; }
[Display(Name = "Le code postal")]
public int CodePostalService { get; set; }
}
and a View which is tight to my ViewModel:
@model MeilleurPresta.Models.ViewModel.ServiceView
@{
ViewBag.Title = "Déposer une offre";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div class="grid_23" id="body">
<h3 style="padding-left: 50px"> Déposer une offre de Service </h3>
<div style="margin-left: 50px">
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<div class="editor-label">
@Html.LabelFor(model => model.NomService)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.NomService)
@Html.ValidationMessageFor(model => model.NomService)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.DescriptionService)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.DescriptionService)
@Html.ValidationMessageFor(model => model.DescriptionService)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.AdresseService)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.AdresseService)
@Html.ValidationMessageFor(model => model.AdresseService)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CodePostalService)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CodePostalService)
@Html.ValidationMessageFor(model => model.CodePostalService)
</div>
<p>
<input type="submit" value="Create" />
</p>
}
</div>
</div>
My controller:
public ActionResult Index()
{
return View();
}
Nothing special, however, when I submit the form, on client validation, it indicates me that the field: Le code postal is required, but it is not in the ViewModel.
I inspect the html source code, it generates the data-val-required class whereas in my ViewModel there are no require attributs.
Where the problems may come from ?
thanks
Because your int isn’t nullable, it’s marked required by default. You can either set the int to int? to make it nullable or you can add this to your application_start to change the default behavior…