我是使用 asp.net mvc 4 开发的新手,当我编辑我的一个模型时,我得到 ModelState.IsValid 总是返回 false。我的模型是下一个:
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; }
}
然后我有下一个表格来编辑 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>
这里的问题在于 Place 对象。用户从下拉列表中选择 ShowTime 的地点,当用户单击保存按钮时,模型返回并且 ModelState.IsValid 返回 false,因为模型中 ShowTime 的 Place 对象从 DropDownList 获取其值,并且仅填充了 ID 属性(记住地点的名称属性是必需的),验证模型状态失败,因为地点的属性名称为空。
如果我从下拉列表中获取 place 对象并且 Place 对象未填充其所有属性,如何使模型有效?我相信在这种情况下,我将数据库模型完全映射到视图上是错误的,也许更好的解决方案是创建这样的 ViewModel,并将模型转换为服务器代码上的 ShowTime
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; }
}
其他选择?