【问题标题】:MVC Drop Down List not mapping to ModelMVC 下拉列表未映射到模型
【发布时间】:2011-02-18 15:34:31
【问题描述】:

我正在尝试使用 EF codefirst 在 MVC 3 中开发应用程序。当我使用 int 属性和约定来设置外键关系时,例如

public class Patient  
{         
     public int ConsultantId {get;set;}
}

然后我设置一个创建和编辑页面并使用 HTML.DropDownListFor Helper 生成可能的顾问列表

 @Html.DropDownListFor(model => model.ConsultantId, ((IEnumerable<Web.Models.Consultant>)ViewBag.PossibleConsultants).Select(option
    => new SelectListItem
    {
        Text = Html.DisplayTextFor(_ => option.ConsultantName).ToString(),
        Value
            = option.ConsultantId.ToString(),
        Selected = (Model != null) && (option.ConsultantId
            == Model.ConsultantId)
    }), "Choose...")

效果很好,但我现在想在患者类上使用 Consultant 对象,例如

 public class Patient  
    {
         public virtual Consultant Consultant {get;set;}
    }

    public class Consultant {
         public virtual ICollection<Patient> Patient {get;set;}
}

我现在尝试使用 DropDownListfor 设置视图,但这次是在 model.Consultant 例如

  @Html.DropDownListFor(model => model.Consultant, ((IEnumerable<Web.Models.Consultant>)ViewBag.PossibleConsultants).Select(option
=> new SelectListItem
{
    Text = Html.DisplayTextFor(_ => option.ConsultantName).ToString(),
    Value
        = option.ConsultantId.ToString(),
    Selected = (Model != null) && (option.ConsultantId
        == Model.Consultant.ConsultantId)
}), "Choose...")

创建和编辑页面加载正确,并且在编辑页面上正确选择了顾问,但是当我发布页面时,ModelState 无效,出现此错误“无法转换
'System.String' 输入 'Web.Models.Consultant"。有谁知道如何使用 DropDownListFor 以便可以将模型映射回对象。

【问题讨论】:

    标签: c# asp.net-mvc entity-framework


    【解决方案1】:

    我找到了适合我的解决方案。使用实体框架 codefirst,您可以在同一类中同时拥有 public int ConsultantId 属性和 public virtual Consultant 属性。数据库中仍然只有一个由 ConsultantId 属性定义的关系。因此,如果这是一个可为空的 int,则关系将是可选的。

    【讨论】:

    • 这真的是最好的方法吗?有没有人可以做到这一点而无需声明单独的 ID 属性?
    【解决方案2】:

    下拉列表选择值(ConsultantId)被绑定到模型上的Consultant属性,该属性是Consultant类型。

    您能否改为将下拉值绑定到 Consultant.ConsultantId?

    例子:

    @Html.DropDownListFor(model => model.Consultant.ConsultantId, // the rest of the statement goes here...
    

    【讨论】:

    • 如果您这样做,则会出现验证错误,因为只有一个 Id 的顾问对象被视为无效。
    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多