我是一个新手,所以我想我的问题是微不足道的。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