I'm newbie developing with asp.net mvc 4, when I edit one of my models I get that ModelState.IsValid is always returning false. My model is the next:
public class ShowTime
{
public int ID { get; set; }
[Display(Name = "Date")]
[Required(ErrorMessage = "Date is required")]
public DateTime Date { get; set; }
[Display(Name = "Time")]
[Required(ErrorMessage = "Time is required")]
public DateTime DateTime { get; set; }
public virtual Place Place { get; set; }
}
public class Place
{
public int ID { get; set; }
[Display(Name = "Place name")]
[Required(ErrorMessage = "Place name is required")]
public string Name { get; set; }
public virtual Address Address { get; set; }
}
Then I have the next form to edit ShowTimes:
<fieldset class="formulari">
<p>
@Html.LabelFor(model => model.Date)
@Html.EditorFor(model => model.Date)
@Html.ValidationMessageFor(model => model.Date)
</p>
<p>
@Html.LabelFor(model => model.DateTime)
@Html.EditorFor(model => model.DateTime)
@Html.ValidationMessageFor(model => model.DateTime)
</p>
<p>
<label>Escenari</label>
@Html.DropDownListFor(model => model.Place.ID, new SelectList(new PlaceBLL().GetAll(), "ID", "Name"))
</p>
<p>
@Html.LabelFor(model => model.Ticket.Price)
@Html.EditorFor(model => model.Ticket.Price, "Ticket", new ViewDataDictionary(Html.ViewDataContainer.ViewData) { TemplateInfo = new System.Web.Mvc.TemplateInfo { HtmlFieldPrefix = "Ticket" } })
@Html.ValidationMessageFor(model => model.Ticket.Price)
</p>
<p>
@Html.LabelFor(model => model.Ticket.BuyingTicketURL)
@Html.EditorFor(model => model.Ticket.BuyingTicketURL)
@Html.ValidationMessageFor(model => model.Ticket.BuyingTicketURL)
</p>
@Html.HiddenFor(model => model.ID)
@Html.HiddenFor(model => model.Ticket.ID)
<br />
<input type="submit" value="Save" />
</fieldset>
The problem here is with Place object. User choose the Place of ShowTime from a Drop drown list and when user click on save button the model is returned and ModelState.IsValid return false, because that Place object from ShowTime in Model is getting its value from a DropDownList and only ID Property is filled (remember Name property of place is Required), validating the ModelState it fails because property Name of Place is empty.
How can I make the model valid if I'm getting the place object from a drop down list and Place object is not filled with all its properties? I'm believe that in that case I'm doing wrong mapping my database model exactly on a view, perphaps a better solution it would be to create a ViewModel like this, and transform the model to ShowTime on server code
public class ShowTimeViewModel
{
public int ID { get; set; }
[Display(Name = "Date")]
[Required(ErrorMessage = "Date is required")]
public DateTime Date { get; set; }
[Display(Name = "Time")]
[Required(ErrorMessage = "Time is required")]
public DateTime DateTime { get; set; }
public int PlaceID { get; set; }
public Ticket Ticket { get; set; }
}
Other alternatives ?