我是新手開發與asp.net mvc 4,當我編輯我的模型之一,我得到ModelState.IsValid始終返回false。我的模型是下一個: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; }
}
然後,我有一個表格編輯放映時間:
<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>
這裏的問題是與地方的對象。用戶從Drop淹沒列表中選擇ShowTime的Place,並且當用戶點擊保存按鈕時,返回模型並且ModelState.IsValid返回false,因爲Model中的ShowTime中的Place對象從DropDownList獲取其值,並且只有ID屬性被填充(記住place的Name屬性是Required),驗證ModelState失敗,因爲Place的Name屬性爲空。
如果我從下拉列表中獲取地點對象並且地點對象沒有被其所有屬性填充,如何使模型有效?我相信,在這種情況下,我正在錯誤地將我的數據庫模型映射到視圖上,使用更好的解決方案創建一個像這樣的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; }
}
其他選擇?