[英]Send Dropdown Selected Value from View to Controller using "DropDownListFor" in MVC
[英]Unable to get a selected foreign key value from dropdown in controller mvc
我有两个表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();
}
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
页面中获取所有状态。我的问题是,当我从下拉列表中选择任何状态并单击创建时,我的客户对象中没有任何状态值,它为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;
}
}
}
假设你有一个StatusId
场在你的Customer
,如果你只是StatusId
你需要调用Html.DropDownListFor
为ForeignKey
您的列属性Customer
,而不是整个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
属性。
注意
正如Stephen Muecke
在评论中提到的那样,使用包含int StatusId
的ViewModel
是一种更干净的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.