C# 在asp.net mvc 5中,仅将不同模型中的必填字段/属性调用到视图模型中,而不使用实体框架
我有两种不同的型号<代码>用户个人详细信息和C# 在asp.net mvc 5中,仅将不同模型中的必填字段/属性调用到视图模型中,而不使用实体框架,c#,asp.net-mvc,C#,Asp.net Mvc,我有两种不同的型号用户个人详细信息和用户教育详细信息 我想将上述两个模型中的一些字段填充到名为UserViewModel的视图模型中 我试过了,但我得到了两个模型的所有字段 public class UserEducationalDetails { public Boolean Undergraduate { get; set; } public Boolean PostGraduate { get; set; } public String CollegeName
用户教育详细信息
我想将上述两个模型中的一些字段填充到名为UserViewModel
的视图模型中
我试过了,但我得到了两个模型的所有字段
public class UserEducationalDetails
{
public Boolean Undergraduate { get; set; }
public Boolean PostGraduate { get; set; }
public String CollegeName { get; set; }
public String SchoolName { get; set; }
}
我希望用户视图模型应该如下所示
public class UserViewModel
{
//Want to view the only following fields from UserPersonalDetails and UserEducationalDetails Model
//From UserEducationalDetails Model
public UserEducationalDetails CollegeName { get; set; }
public UserEducationalDetails SchoolName { get; set; }
//From UserEducationalDetails Model
public UserPersonalDetail FullName {get; set;}
public UserPersonalDetail MarriedStatus { get; set; }
}
您误解了模型类的工作方式。例如,定义此项时:
public class UserViewModel
{
public UserEducationalDetails CollegeName { get; set; }
}
这并不意味着CollegeName取自UserEducationalDetails
模型,而是意味着它是一个UserEducationalDetails模型。这显然不是你想要的。您要做的是在构建UserViewModel
时读取属性,如下所示:
public class UserViewModel
{
// Types reflect the types used in the models
public string CollegeName { get; private set; }
public string SchoolName { get; private set; }
public string FullName {get; private set;}
public string MarriedStatus { get; private set; }
public UserViewModel(UserEducationalDetails ued, UserPersonalDetails upd)
{
// Copy the properties that are relevant to this object
CollegeName = ued.CollegeName;
SchoolName = ued.SchoolName;
FullName = upd.FullName;
MarriedStatus = upd.MarriedStatus;
}
}
所有这些,
CollegeName
,school name
等都应该是string
s。此CollegeName和school name是UserEducationalDetails模型的一部分。我希望这些文件应该在UserviewModel中。
public class UserViewModel
{
// Types reflect the types used in the models
public string CollegeName { get; private set; }
public string SchoolName { get; private set; }
public string FullName {get; private set;}
public string MarriedStatus { get; private set; }
public UserViewModel(UserEducationalDetails ued, UserPersonalDetails upd)
{
// Copy the properties that are relevant to this object
CollegeName = ued.CollegeName;
SchoolName = ued.SchoolName;
FullName = upd.FullName;
MarriedStatus = upd.MarriedStatus;
}
}