【发布时间】:2012-03-18 10:49:29
【问题描述】:
我是新手,所以我想我的问题在某种程度上是微不足道的。
我使用 CodeFirst 创建了一个简单的数据库。我有一个名为Person 的实体和另一个名为Location 的实体。 Person 有一个名为 LocationId 的 ForeignKey 属性和另一个类型为 Location 的属性以供参考。
我创建了一个视图,其中有一个表单,我可以通过它创建新的Person 记录。
其中一个表单字段是用于人员“位置”的 DropDownList。它接受一个 Id 值并将其分配给Person 的LocationId 属性。
此视图引用create 控制器操作,该操作接收Person 作为参数,并使用person 属性绑定到表单字段。然后,它在DBContext 中执行SaveChanges() 并重定向到另一个名为details 且具有特定Person 'Id' 的Action。
Details 在收到的 Id 上创建一个 find 并将结果(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? -
如果您发布 Person/Location 类和定义外键的配置类将有助于识别问题
-
'LocationValue' 是字符串类型。它包含位置的名称。 TextBox 用于输入,我只需要介绍它的价值..
-
Person 类有 Location 属性吗?还是不行?
-
Jayanga:是的,如前所述……
标签: asp.net-mvc entity-framework code-first