从不同的表访问用户名
本文关键字:访问 用户 | 更新日期: 2023-09-27 18:28:03
我试图在表格中包括谁创建或提交了学校申请。我正在visual studio 2012中使用C#MVC4进行开发。我是这个mvc c#的新手,所以我相信这对所有人来说都很容易。
这是我的视图详细信息.cshtml:
@model Models.Schools
/*I get an error when i do this, it looks like i can only include one model, as school name, and address gets to be undefined.*/
@model Models.whoCreated
//this is coming from Models.Schools
school name:
address:
/*this is coming from Models.WhoCreated
Schools and WhoCreated are both tables in db and share common id.
any idea on how to achieve this? also i would like to show this field only to admin, and I am using Membership.getUser (all valid users are stored in my db, with admin or just regular user status)*/
created by:
您应该创建一个新模型,该模型包含视图中需要的所有字段。您需要知道数据库中的表和您显示的模型是(或者应该至少是)两个不同的类,您从数据库中获取数据并将其放入视图中显示的模型类中。
所以你的模型类应该看起来像:
public class SchoolModel
{
public string SchoolName {get; set;}
public string Address {get;set;}
public string CreatedBy {get;set;}
}
然后在控制器动作中:
public class HomeController : Controller
{
public ActionResult Index()
{
//getting info from database to variables
SchoolModel schoolModel = new SchoolModel();
schoolModel.SchoolName = //school retrieved from database, something like context.Schools.Name
schoolModel.Address = // something like context.Schools.Address
schoolModel.CreatedBy = // context.Users.Where(x => x.id == yourIdOrSomething)
return View(schoolModel);
}
}
然后在default.cshtml 中
@model Models.SchoolModel
school: @Model.SchoolName
address: @Model.Address
created by : @Model.CreatedBy