【发布时间】:2018-07-06 17:48:31
【问题描述】:
我的开发环境是 ASP.NET MVC 5,使用 Entity Framework 6,使用代码优先工作流。
我的问题:尝试向数据库添加新记录时,我的两个下拉列表中的值未包含在内。所有其他字段确实都保存到数据库中。
我将 ViewModel 传递给相关视图:
public class NewItemViewModel
{
public IEnumerable<Category> Categories { get; set; }
public Item Item { get; set; }
public IEnumerable<Donor> Donors { get; set; }
}
我正在使用的领域模型:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Quantity { get; set; }
public bool IsActive { get; set; }
public Category Category { get; set; }
public Donor Donor { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Donor
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return FirstName + " " + LastName; } }
public string Email { get; set; }
}
相关控制器:这个 New() 操作只是用来将数据传递给视图以提交表单
public ActionResult New()
{
var itemCategories = _context.ItemCategory.ToList();
var donors = _context.Donors.ToList();
var viewModel = new NewItemViewModel
{
Categories = itemCategories,
Donors = donors
};
return View(viewModel);
}
这是我将提交的数据添加到数据库的实际操作:
// Create a new item.
[HttpPost]
public ActionResult Create(Item item)
{
_context.Items.Add(item);
_context.SaveChanges();
return RedirectToAction("Index", "Item");
}
最后,视图本身(我将在这里最小化代码):
@using (Html.BeginForm("Create", "Item"))
{
<div class="form-group">
@Html.LabelFor(m => m.Item.Donor)
@Html.DropDownListFor(m => m.Item.Donor, new SelectList(Model.Donors, "Id", "FullName"), "Who donated this item?", new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Item.Category)
@Html.DropDownListFor(m => m.Item.Category, new SelectList(Model.Categories, "Id", "Name"), "Select Item Category", new { @class = "form-control" })
</div>
}
重申我遇到的问题:Category 和 Donor 下拉列表的值未保存到数据库中,而其他(非导航属性?)名称、描述、数量等工作正常。
我是否以正确的方式使用 ViewModel?我的印象是 MVC 框架知道如何处理在 Create() 操作中传递 Item 对象参数 - 在 Item 实体中映射它需要的内容。
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
在
NewItemViewModel中,您尚未创建属性来保存下拉列表中的选定值
标签: asp.net-mvc entity-framework