首页 > 解决方案 > DropDownList 没有将值传递给我的控制器

问题描述

我已经使用 html 帮助程序的 dropdownlist 成功填充了我的下拉列表,但是当我提交表单时,所选项目的值没有与模型一起传递到操作结果中。这是我的代码示例

客户模型

public class Customer
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }

    [StringLength(11)]
    [Display(Name="Date of birth")]
    public string BirthDate { get; set; }

    public bool IsSubscribedToNewsLetter { get; set; }

    public MembershipType MembershipType { get; set; }

    [Display(Name = "Membership type")]
    public MembershipType MembershipTypeId { get; set; }
}

会员类型模型

public class MembershipType
    {
        public int Id { get; set; }
        [StringLength(15)]
        public string Name { get; set; }
        public short SignUpFee { get; set; }
        public byte DurationInMonths { get; set; }
        public byte DiscountRate { get; set; }
    }

客户视图模型

   public class NewCustomerViewModel
    {
        public IEnumerable <MembershipType>MembershipTypes { get; set; }
        public Customer Customer { get; set; }
    }

看法

@model MovieApp.ViewModels.NewCustomerViewModel
@{
    ViewBag.Title = "New";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>New Customer</h2>
@using (Html.BeginForm("Create", "Customers"))

{
    <div class="form-group">
        @Html.LabelFor(c => c.Customer.Name)
        @Html.TextBoxFor(c => c.Customer.Name, new { @class = "form-control" })
    </div>
<div class="form-group">
    @Html.LabelFor(c => c.Customer.BirthDate)
    @Html.TextBoxFor(c => c.Customer.BirthDate, new { @class = "form-control" })
</div>

<div class="form-group">
    @Html.LabelFor(c => c.Customer.MembershipType)
    @Html.DropDownListFor(c => c.Customer.MembershipType
    ,new SelectList(Model.MembershipTypes, "Id","Name")
    ,"Select Membership Type"
    ,new { @class = "form-control" })
</div>


<div class="checkbox">
    <label>
        @Html.CheckBoxFor(c => c.Customer.IsSubscribedToNewsLetter) Subscribed to newsletter?
    </label>
</div>

<button type="submit" class="btn btn-primary">Save</button>
}

行动

public ActionResult New()
        {
            var  DBmebershipTypes= _context.MembershipTypes.ToList();
            var ViewModel = new NewCustomerViewModel()
            {
                MembershipTypes = DBmebershipTypes

            };
            return View(ViewModel);
        }

事后行动

 [HttpPost]
        public ActionResult Create(Customer customer)
        {
             _context.Customers.Add(customer);
             _context.SaveChanges();
             return RedirectToAction("Index", "Customers");
        }

当我调试程序时,所有输入的值都在内存中,但是当它必须保存到数据库时,下拉列表选择不会被保存。

标签: asp.net.netasp.net-mvc

解决方案


更新您的Customer班级,您的 MembershipTypeId 类型错误,int希望这对您有用。

[Display(Name = "Membership type")]
public int MembershipTypeId { get; set; }

推荐阅读