0

我试图在表格中只包括谁创建或提交了学校请求。我正在 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: 
4

1 回答 1

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
于 2013-08-18T23:26:21.067 回答