简体   繁体   中英

Sending Viewmodel object to a razor view in ASP .Net MVC

In my MVC Project , I have a Student model class and a Department model class. To establish one-to-many relationship I had a foreign key DepartmentID in the Student Model Class.

    public class Student
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StudentId { get; set; }
    public String LastName { get; set; }
    public String FirstName { get; set; }
    public String UserName { get; set; }
    public String Password { get; set; }

    [ForeignKey("Department")]
    public int DepartmentID { get; set; }

}

and

    public class Department
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int DepartmentID { get; set; }

    [Required(ErrorMessage="Department Name cannot be empty")]
    public String DepartmentName { get; set; }

    [Required(ErrorMessage = "Department Code cannot be empty")]
    public String DepartmentCode { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

but instead of DepartmentID that is there in the Student Class I wanted the user to see DepartmentName instead . so the StudentViewModel Class is as below :

    //View Model
public class StudentViewModel
{
    public Student Student { get; set; }

    public int StudentId { get; set; }

    [Display(Name="StudentName")]
    [Required(ErrorMessage="Student Name cannot be left blank")]
    public String StudentFullName
    {
        get
        {
            return String.Format("{0} {1}", Student.FirstName, Student.LastName);
        }
    }

    public String UserName { get; set; }

    [DataType(DataType.Password)]
    public String Password { get; set; }

    [DataType(DataType.Password)]
    [Compare("Password",ErrorMessage="Passwords do not match")]
    [Display(Name="Confirm Password")]
    public String C_Password { get; set; }

    [Display(Name = "Department Name")]
    public String DepartmentName { get; set; }

}

but how would I get department name in my controller action method that displays list of all the students that is there in DB.

    public ActionResult MyAction()
    {
        StudentContext context = new StudentContext();
        var students = context.Students.ToList();
        var departments = context.Departments.ToList();
        var student_dept_lst = new List<StudentViewModel>();
        var departmentName = String.Empty;

        foreach(var s in students)
        {
            var student_dept = new StudentViewModel();
            student_dept.DepartmentName =  from d in departments where d.DepartmentID == s.DepartmentID select d.DepartmentName;
        }

        return View(student_dept_lst ); 
    }

How would I link DepartmentName to each student object in the list that I get from Context ? I know this is trivial . But please help me . Thanks in advance.

The correct approach is to add a Departement navigational property into your Student Class like this:

public class Student
{
    // Your properties you have already created still reamin here

    public Department Department { get; set; }
}

Then do some refactoring into your action like this:

StudentContext context = new StudentContext();
var viewModels = context.Students
    .Include(s => s.Department) // tell EF to eager load the related department for each student
    .Select(s => new StudentViewModel // this make a projection to your view model
    {
        Student = s,
        DepartmentName = s.Department.DepartmentName
        // Set all properties you need
    }).ToList();

return View(viewModels); 

Looks ok what you got, but you're not adding student_dept to the list of studentviewmodel.

Also, you should pick an option - if you have Student on your view model, you don't need each property from Student (username, password, etc). You can just reference via the Student object. Or keep those properties on view model and get rid of Student. And then, set the properties accordingly on your view model.

foreach(var s in students)
{
    var student_dept = new StudentViewModel();
    student_dept.DepartmentName =  from d in departments where d.DepartmentID == s.DepartmentID select d.DepartmentName;
    student_dept.Student = s;
    //set other properties accordingly
    student_dept_lst.Add(student_dept);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM