无法从控制器mvc的下拉列表中获取选定的外键值
本文关键字:获取 键值 下拉列表 控制器 mvc | 更新日期: 2023-09-27 18:21:16
我有两个表Customer
和Status
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();
}
创建.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
页面My中获取所有状态问题是当我从下拉列表中选择任何状态并单击创建时不要在我的客户对象中获得任何状态值,它是空
有以下异常{"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; }
}
}
客户.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;
}
}
}
假设您的Customer
中有一个StatusId
字段,如果除了StatusId
之外,您需要为Customer
的ForeignKey
列属性调用Html.DropDownListFor
,而不是整个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
属性。
注意
使用包含int StatusId
的ViewModel
是一种更干净的方式,Stephen Muecke
在评论中也提到了这一点。