我在這裏搜索了很多,找到這樣的事情,使下拉列表
這是我的模型:mvc4下拉列表插入空
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; }
}
這是我的控制器: 這把我的數據下拉列表...
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; }
的問題是:我在下拉列表看到數據從db.Categories但是當我選擇從這個DDL一些選項,並增加對其他組件有些價值(來自EditorFor)。他們已經插入數據庫沒有選擇類別從ddl而不是類別我有NULL.Thanks耐心 – Krasimir 2013-03-05 21:06:01
您的利潤類是否有CategoryName或CategoryID。在你的例子中它是CategoryName,但是你設置你的dropdownlist返回的是什麼? – 2013-03-05 21:13:58
是類別CategoryName是一個類別列表還是一個類別? – 2013-03-05 21:28:42