我是一個新手,所以我想我的問題是微不足道的。asp.net mvc displayFor不顯示子實體值
我用CodeFirst創建了一個簡單的數據庫。我有一個名爲Person
的實體,另一個名爲Location
。 Person
有一個名爲LocationId
的ForeignKey
屬性和Location
類型的另一個屬性以供參考。
我創建了一個視圖,其中有一個窗體可以用來創建新的Person
記錄。
其中一個表單域是一個人的'位置'的DropDownList。它需要一個Id值並將其分配給Person
的LocationId
屬性。
該視圖引用create
控制器操作,該操作接收Person
作爲參數,並使用person
屬性綁定到表單字段。然後,它執行SaveChanges()
到DBContext
,並將其重定向到具有特定Person'Id`的名爲details
的另一個Action。
Details
在接收到的Id上產生一個find
,並將結果(Person)發送到視圖進行展示。
這是我的問題:
我嘗試顯示我通過的特定'Person'的位置txt,並且什麼也沒得到。 我這樣做:
@Html.DisplayFor(model => model.Location.LocationValue)
模型當然是一個'人'。 爲什麼我對此沒有任何價值?
下面的代碼:
public class Person
{
public int PersonId { get; set;
public string LocationId { get; set; }
...
public virtual Location Location { get; set; }
}
public class Location
{
public int LocationId { get; set; }
public string LocationValue { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
public ActionResult Detailes(int id)
{
Person person = db.Persons.Find(id);
return View(person);
}
[HttpPost]
public ActionResult AddPerson(Person person)
{
if (ModelState.IsValid)
{
db.Persons.Add(person);
db.SaveChanges();
return RedirectToAction("Detailes", new {id = person.PersonId});
}
return View(GetAddPersonViewModel());
}
這裏的模型是形式的視圖模型
@Html.DropDownListFor(model => model.Person.LocationId, Model.LocationsList)
再次,在 '細節' 觀點的陳述:
@Html.DisplayFor(model => model.Location.LocationValue)
謝謝。
什麼是位置值的類型?你爲什麼不使用'Html.TextBoxFor'? – gideon 2012-03-18 10:57:40
如果您發佈定義外鍵的Person/Location類和配置類將有助於確定問題 – Jayanga 2012-03-18 11:15:00
'LocationValue'是字符串類型。它擁有該位置的名稱。 TextBox是用於輸入,我只需要一個它的值的演示文稿。 – 2012-03-18 11:16:44