由于下拉列表,ModelState.IsValid返回false

时间:2012-12-08 14:54:24

标签: asp.net-mvc

我是用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对象。用户从Drop drown列表中选择Place of ShowTime,当用户单击save按钮时,将返回模型,ModelState.IsValid返回false,因为Model中ShowTime的Place对象从DropDownList获取其值,并且只填充ID属性(记住Place的Name属性是必需的),验证ModelState失败,因为属性Name of Place为空。

如果我从下拉列表中获取place对象并且Place对象没有填充其所有属性,那么如何使模型有效?我相信在这种情况下,我错误地将我的数据库模型映射到视图上,perphaps是一个更好的解决方案,它将创建一个像这样的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; }
}

其他替代方案?

1 个答案:

答案 0 :(得分:1)

名称永远不会发送到服务器。这就是<select>元素的工作原理。它只将选定的值发送到服务器(即ID)。因此,使用视图模型并删除此Name属性。使ID属性成为可以为null的整数,并使用Required属性进行修饰,强制用户在DropDown中选择一个值。一旦在POST操作中获得了ID,您就可以查询数据库,以便在需要时检索相应的名称。