我试图在表单中包含创建或提交学校请求的人员。我正在使用Visual Studio 2012中的C#MVC4开发。我是这个mvc c的新手#所以我相信这对所有人都很容易。
这是我的观点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 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:
答案 0 :(得分:2)
您应该创建一个新模型,其中包含您在查看时需要的所有字段。您需要知道您显示的数据库和模型中的表是(或应该至少)是两个不同的类,您从数据库获取数据并将其放入您在视图上显示的模型类中。
所以你的模型类应该是这样的:
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