gpt4 book ai didi

c# - 在 Razor MVC3 中使用 ViewModel 在单个 View 中显示多个模型( View 中只有详细信息)

转载 作者:太空狗 更新时间:2023-10-30 00:53:58 25 4
gpt4 key购买 nike

我的任务是将多个 models 显示到一个 View 中。我已经为我的要求创建了一个 ViewModel,但我没有满足我的要求。请查看下面的代码并纠正我哪里出错了???

public partial class StudentsDetail
{
public int StudentID { get; set; }
public int ParentID { get; set; }
public string StudentName { get; set; }
public string Gender { get; set; }
public string FatherName { get; set; }
public string MotherName { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }

public virtual ParentsDetail ParentsDetail { get; set; }
public virtual SchoolDetail SchoolDetail { get; set; }
}

//模型2

 public partial class ParentsDetail
{
public ParentsDetail()
{
this.StudentsDetails = new HashSet<StudentsDetail>();
}

public int ParentID { get; set; }
public string Occupation { get; set; }
public string Organization { get; set; }
public string AnnualIncome { get; set; }

public virtual ICollection<StudentsDetail> StudentsDetails { get; set; }
}

//我创建的ViewModel

 public class ParentsInformationViewModel
{
public List<StudentsDetail> StudentsDetails { get; set; }
public List<ParentsDetail> ParentsDetails { get; set; }

public ParentsInformationViewModel(List<StudentsDetail> _studentDetails, List<ParentsDetail> _parentsDetails) //Should i pass all the required parameters that i want to display in view ????
{
StudentsDetails = _studentDetails;
ParentsDetails = _parentsDetails;

}

//最后这是我在 StudentController 中定义的方法(我在正确的地方/方式定义它了吗??)

public ActionResult StudentViewModel()
{
ViewBag.ParentsDetail = new ParentsDetail(); //ParentsDetail is my controller
List<StudentsDetail> studentListObj = StudentsDetailsDAL.GetStudentDetails();
List<ParentsInformationViewModel> ParentInfoVMObj = new List<ParentsInformationViewModel>();
//foreach (var student in studentListObj)
//{
// ParentInfoVMObj.Add(new ParentsInformationViewModel(student.StudentID, student.ParentID));

//}
//ParentInfoVMObj.Add(ParentInfoVMObj); /// don't know how to call the required viewmodel
return View(ParentInfoVMObj);
}

我知道上面的 ViewModel 方法是错误的,但是我不知道如何使用它或者哪里出错了。我想在 View 中将 ViewModel 显示为详细 View 。请纠正我,因为我是 MVC3 的初学者。

提前致谢!!

最佳答案

在您的 Controller 中,按如下方式定义您的操作方法。

public ActionResult ParentsDetails()
{
var studentDetails = new List<StudentDetail>();
var parentDetails = new List<ParentsDetail>();

// Fill your lists here, and pass them to viewmodel constructor.
var viewModel = new ParentsInformationViewModel(studentDetails, parentDetails)

// Return your viewmodel to corresponding view.
return View(viewModel);
}

在您的 View 中定义您的模型。

@model MySolution.ViewModels.ParentsInformationViewModel

关于c# - 在 Razor MVC3 中使用 ViewModel 在单个 View 中显示多个模型( View 中只有详细信息),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14496568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com