【发布时间】:2019-12-10 12:39:46
【问题描述】:
我已经使用 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; }
}
MembershipType 模型
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");
}
当我调试程序时,所有输入的值都在内存中,但是当它必须保存到数据库时,下拉列表选择并没有保存。
【问题讨论】:
-
请看这个已经在这篇文章中给出答案:Link
-
@HirenPatel 不在那篇文章中没有这个问题的答案
标签: asp.net .net asp.net-mvc