我在这里搜索了很多,找到了这样的东西来制作下拉列表
,这是我的模型:
public class Profits
{
[Key]
public int Id { get; set; }
public double Value { get; set; }
public string Description{ get; set; }
[DataType(DataType.Date)]
public DateTime DateInput { get; set; }
public UserProfile User { get; set; }
public Categories CategoryName { get; set; }//foreign key
public int CategoryID { get; set; }
}
public class Categories
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public UserProfile User { get; set; }
}
这是我的控制器:这会将我的数据传递给 dropDownList...
public ActionResult Create()
{
var dba = new WHFMDBContext();
var query = dba.Categories.Select(c => new { c.Id, c.Name });
ViewBag.Id = new SelectList(query.AsEnumerable(), "Id", "Name", 3);
return View();
}
[HttpPost]
[InitializeSimpleMembership]
public ActionResult Create(Profits profits)
{
var user = db.UserProfiles.FirstOrDefault(x => x.UserId == WebSecurity.CurrentUserId);
var profit = new Profits
{
Value= profits.Value,
Description = profits.Description,
DateInput =profits.DateInput,
CategoryName =profits.CategoryName,// ???
User = user,
};
db.Profits.Add(profit);
db.SaveChanges();
return RedirectToAction("Index");
}
我的观点 :
@model WebHFM.Models.Profits
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Profits</legend>
<div class="editor-field">
@Html.LabelFor(model => model.CategoryName)
</div>
<div class="editor-field">
@Html.DropDownList("Id", (SelectList) ViewBag.Id, "--Select One--")
@Html.ValidationMessageFor(model => model.CategoryName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Value)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Value)
@Html.ValidationMessageFor(model => model.Value)
</div>...
这将数据插入数据库,但我错过了什么CategoryName_Id
?这是利润中类别的外 NULL
键CategoryName = profits.CategoryName
public Categories CategoryName { get; set; }