我有两张表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
页面中获取所有状态 问题是当我从下拉列表中选择任何状态并单击“创建i”时 在我的客户对象中没有得到任何状态值它是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;
}
}
}
答案 0 :(得分:2)
假设您StatusId
中有Customer
字段,如果除了StatusId
,则需要为Html.DropDownListFor
列ForeignKey
列属性致电Customer
{1}}而不是整个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
属性。
注意强>
使用包含ViewModel
的{{1}}是Stephen Muecke
在评论中提到的更为干净的方法。