asp.net - 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");
}
当我调试程序时,所有输入的值都在内存中,但是当它必须保存到数据库时,下拉列表选择不会被保存。
解决方案
更新您的Customer
班级,您的 MembershipTypeId 类型错误,int
希望这对您有用。
[Display(Name = "Membership type")]
public int MembershipTypeId { get; set; }
推荐阅读
- php - PHP 将 RGB 数组转换为字符串变量
- .net - 是否需要为客户端和管理部分分离 API
- python - 过滤来自特定用户的带有主题标签的推文
- karate - 使用 karateConfig.js 时线程“主显示”中的异常
- c# - Microsoft Graph API - 权限不足,Request_ResourceNotFound - Azure 权限问题
- angular - 如何使用谷歌地图根据获取的纬度和经度定位地图
- reactjs - 任何人都可以帮助我应该如何开始或给我一个我可以编写的可能单元测试的抽象形式
- jquery - AJAX POST 中的 405 Method Not Allowed 错误
- python - 在使用 numpy 唯一计数时通过避免 python 循环来提高性能
- azure - 关于通过 VM 上的 azure runbook 安装工具