问题背景:在Asp.Net中使用Html.EditorFor方法生成表单时,外键ID来自不同的表,需要将其转换为相应的名称显示在表单中。
解决方法:
public class MyViewModel
{
public int ForeignKeyId { get; set; }
public string ForeignKeyName { get; set; }
}
public ActionResult Edit(int id)
{
MyViewModel viewModel = new MyViewModel();
// 查询外键表获取外键名称
ForeignKeyTable foreignKey = dbContext.ForeignKeyTables.Find(viewModel.ForeignKeyId);
viewModel.ForeignKeyName = foreignKey.Name;
return View(viewModel);
}
@Html.LabelFor(model => model.ForeignKeyId, "Foreign Key Name", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.DisplayFor(model => model.ForeignKeyName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ForeignKeyName, "", new { @class = "text-danger" })
这样,通过以上步骤,就可以将外键ID从不同的表中转换为相应的名称并显示在表单中了。