I am developping an MVC 4 application and I have some troubles.
Here is an extract of my model:
public class RegistryModel
{
[DisplayName("Registry id")]
public int registryId { get; set; }
[Required]
[DataType(System.ComponentModel.DataAnnotations.DataType.Date)]
[DisplayName("Reception date")]
public DateTime? receivedDate { get; set; }
[Required]
[DisplayName("Source")]
public Source source { get; set; }
}
Source object:
public class Source
{
public virtual string sourceCode { get; set; }
public virtual string fullName { get; set; }
public virtual string shortName { get; set; }
public virtual string type { get; set; }
public virtual IList<Registry> registryList { get; set; }
}
Controller:
public ActionResult Create()
{
var sourceRepo = new Repository<DTOS.Source>(MvcApplication.UnitOfWork.Session);
IEnumerable<SelectListItem> sourcesEnum = sourceRepo.FilterBy(x=>x.type.Equals("C")).Select(c => new SelectListItem { Value = c.sourceCode, Text = c.fullName });
ViewBag.Sources = sourcesEnum;
return View();
}
And finally the view
@model Registry.Models.RegistryModel
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>New Registry</legend>
<div class="editor-label">
@Html.LabelFor(model => model.source)
</div>
<div class="editor-field">
@Html.DropDownListFor(Model => Model.source.sourceCode, (IEnumerable<SelectListItem>)ViewBag.Sources, String.Empty)
@Html.ValidationMessageFor(model => model.source)
</div>
If I select a source from the dropdownlist, it works fine. However, if I submit it without selecting any, I don’t have the error message, even if it is annotated as [Required] in the model.
After debugging the HttpPost Create at controller level, I see that the source member of the returned RegistryModel is instanciated, but all its member are null (sourceCode, fullName, etc).
Why is MVC instanciating the source member of the model if I did not select any source in the dropdownlist before submitting the form ?
I tried to modify the vue by this:
@Html.DropDownListFor(Model => **Model.source**, (IEnumerable<SelectListItem>)ViewBag.Sources, String.Empty)
This time I have the error message if I submit without selecting any source, but if I select one, I have another error message after submitting, saying ‘The value user code selected before submitting is invalid’
Any help would be most appreciated !
B.
I believe the model binder will create a Source object and then try to fill in the values it has (whether there or not) when submitting the form. The RequiredAttribute is not acting as you may thin. See here:
http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html