[英]ASP.NET MVC2 and Entity Framework 4 Generating Model from Database without duplicating Membership Models
[英]call only required field/attribute from the different models into a view model in asp.net mvc 5 without using entity framework
我有两个不同的模型。 UserPersonalDetail
和UserEducationalDetails
我想将上述两个模型中的一些字段填充到名为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 UserPersonalDetail
{
public String FullName {get; set;}
public string FirstName { get; set; }
public string LastName { get; set; }
public string FatherName { get; set; }
public string placeofBirth { get; set; }
public string MarriedStatus { 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; }
}
这并不意味着UserEducationalDetails
取自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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.