私はここでたくさん検索し、このようなものを見つけてドロップダウンリストを作成します
これは私のコントローラです:これは私のデータを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.DropDownList("Id", (SelectList) ViewBag.Id, "--Select One--")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CategoryName.Id)
@Html.ValidationMessageFor(model => model.CategoryName.Id)
</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 これは Profits のカテゴリへの外部キーです public Categories CategoryName { get; set; }