无法从控制器mvc中的下拉列表中获取选定的外键值

时间:2015-11-10 10:51:09

标签: c# asp.net-mvc asp.net-mvc-4

我有两张表CustomerStatus

CustomerController.cs

// GET: Customers/Create
        public ActionResult Create()
        {
            P  var Query = from d in db.Status
                        orderby d.Name
                                   select d;
            ViewBag.Status = new SelectList(Query, "myStatusId", "Name", selected);
            return View();
        }

Create.cshtml

<div class="editor-field">
            @Html.DropDownListFor(model => model.status, ViewBag.Status as SelectList, String.Empty)
            @Html.ValidationMessageFor(model => model.status)
        </div>
  

现在,我可以在Customer/Create.cshtml页面中获取所有状态   问题是当我从下拉列表中选择任何状态并单击“创建i”时   在我的客户对象中没有得到任何状态值它是NULL

有以下例外情况 {"The parameter conversion from type 'System.String' to type 'Status' failed because no type converter can convert between these types."}

CustomerController.cs

 [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Customer customer)
        {
            if (ModelState.IsValid)
            {

模型类 MyIdClass.cs

public class MyIdClass
    {

        private Guid myIDField;


        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public Guid myID
        {
            get { return myIDField; }
            set { myIDField = value; }
        }

    }

Customer.cs

public partial class Customer : MyIdClass
    {
        public string Name {get; set;}

        private Status statusField;

          public Status status
        {
            get
            {
                return this.statusField;
            }
            set
            {
                this.statusField = value;
            }
        }
}

状态.cs

 public partial class Status : MyIdClass {
         private string nameField;

  public string name {
            get {
                return this.nameField;
            }
            set {
                this.nameField = value;
            }
        }

 }

1 个答案:

答案 0 :(得分:2)

假设您StatusId中有Customer字段,如果除了StatusId,则需要为Html.DropDownListForForeignKey列属性致电Customer {1}}而不是整个ForeignKey对象属性:

@Html.DropDownListFor(model => model.StatusId, ViewBag.Status as SelectList, String.Empty)

但是如果你没有这样的财产并且你怀疑Status,那么你可以这样使用它:

@Html.DropDownListFor(model => model.status.myStatusId, ViewBag.Status as SelectList, String.Empty)

@*/
If you need the value of model.status.Name 
You can set it using a simple script on the dropdown change, 
otherwise, you don't need to use a hiddenfor
*@
@Html.HiddenFor(model => model.status.Name)

然后在Post中,它应该使用值初始化您的customer.Status属性。

注意

使用包含ViewModel的{​​{1}}是Stephen Muecke在评论中提到的更为干净的方法。