C# 从不同的表访问用户名
我试图在表格中包括创建或提交学校申请的人。我正在visual studio 2012中使用C#MVC4进行开发。我是mvc的新手,所以我相信这对所有人来说都很容易 以下是my view details.cshtml:C# 从不同的表访问用户名,c#,asp.net,asp.net-mvc,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,我试图在表格中包括创建或提交学校申请的人。我正在visual studio 2012中使用C#MVC4进行开发。我是mvc的新手,所以我相信这对所有人来说都很容易 以下是my view details.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 un
@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
ViewModels:您可以将WhoCreated信息包括在学校模型中,或者将WhoCreated信息添加到viewbag中并从那里访问它。在开始作业之前,请确保首先了解您正在做的事情:谢谢大家的回答,我已经创建了所有的控制器/模型/视图等,但是,我对如何在一个视图中包含两个不同的模型有点迷茫。再次感谢。我已经编辑了你的标题。请看,“,其中的共识是“不,他们不应该”。谢谢迈克尔,我已经有了我的模型和控制器以及我所有的观点。我对如何在视图中包含“Createdby”部分有点迷茫。“schoolModel.CreatedBy=//”这很有帮助,但我对“details.cshtml”更感兴趣