MVC下拉列表不会映射到模型 [英] MVC Drop Down List not mapping to Model

查看:333
本文介绍了MVC下拉列表不会映射到模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图开发使用EF codefirst在MVC 3的应用程序。当我使用INT属性和公约例如建立外键关系

I'm trying to develop an application in MVC 3 using EF codefirst. When I use int properties and convention to set up foreign key relationships e.g.

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

然后我设置的创建和编辑页面,并使用HTML.DropDownListFor助手产生的可能的顾问名单

I then setup an create and edit page and use the HTML.DropDownListFor Helper to produce a list of possible consultants

 @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...")

这工作得很好,但我现在想搬到有病人类例如顾问对象。

Which works fine, but I now want to move to having the Consultant object on the patient class e.g.

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

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

我现在使用DropDownListfor但这次的model.Consultant例如。

I now try to setup the view using the DropDownListfor but this time on the model.Consultant e.g.

  @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因此模型可以被映射回一个对象。

The create and edit page load correctly and the consultant is correctly selected on the edit page but when I post the page the ModelState is InValid on this error "Can't convert
'System.String' to type 'Web.Models.Consultant". Does anyone know how to use the DropDownListFor so the Model can be mapped back to an object.

推荐答案

我发现,我的解决方案。使用entitiy框架codefirst你可以同时拥有公众诠释ConsultantId财产,在同一个类中的公共虚拟财产顾问。还有在其由ConsultantId属性定义的数据库只有一个关系。因此,如果这是一个可空INT的关系,将是可选的。

I've found a solution that works for me. Using entitiy framework codefirst you can have both the public int ConsultantId property and the public virtual Consultant property in the same class. There is still only one relationship in the database which is defined by the ConsultantId property. So if this is a nullable int the relationship would be optional.

这篇关于MVC下拉列表不会映射到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆