如何将数据从多个模型传递到视图?

时间:2018-03-15 13:35:58

标签: c# asp.net-mvc razor

我有3个模特

学生

interface A {}
abstract class B implements A {}
class C extends B { /*few fields*/ }
class D extends B { /*few different fields*/ }

public void doSomething(Class<A> clazz) {
    if(clazz.isAssignableFrom(B)) {
        doSomethingElse((Class<? extends B>)clazz); // casting is good, but cannot pass this way to doSomethingElse
    }
}

public <T extends B> void doSomethingElse(Class<T> clazz) {
    if(clazz.isAssignableFrom(C)) {
        // do something with C fields
    } else if(clazz.isAssignableFrom(D)) {
        // do something with D fields
    }
}

主题

public class Student
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; } //primary key


    [RegularExpression(@"^[ A-Za-z]*$", ErrorMessage = "Only Alphabet allowed")]
    [Required] //Because you can't leave this field empty
    public string Name { get; set; }

    [RegularExpression(@"^[ A-Za-z]*$", ErrorMessage = "Only Alphabet allowed")]
    [Required]
    public string LastName { get; set; }

    [RegularExpression(@"^(\d{1,3})/\d{4}$", ErrorMessage = "Format has to be 1-3digit number/year; example 100/2015")]
    [Required]
    public string BI { get; set; }

}

考试

public class Subject
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [RegularExpression(@"^[ A-Za-z0-9]*$", ErrorMessage = "Only Alphabet and numbers allowed")]
    [Required]
    public string SubjectName { get; set; }
}

视图模型

public class Exam
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    public int StudentID { get; set; }

    public int SubjectID { get; set; }

    [Range(6, 10)]
    public int Grade { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime EnrollmentDate { get; set; }
}

我想将StudentsController中的数据传递给edit.cshtml,以便能够从下拉菜单中编辑SubjectName和Grade。我还从这3个创建了ViewModel,并包含了ViewModel。我只是不知道如何将ViewModel从控制器传递到视图。有什么想法吗?

控制器编辑

public class ViewModel
{
    public Student Students;
    public IEnumerable<Exam> Exams;
    public IEnumerable<Subject> Subjects;

}

1 个答案:

答案 0 :(得分:3)

我认为docker run -it -p 9200:9200 -d --net="host" --env-file ~/myapp-local.env --name myapp myapp 应该只包含您要在viewmodel上使用的属性,而不是整个view

但你可以像这样传递model

ViewModel

然后在public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var student = await _context.Student.SingleOrDefaultAsync(m => m.ID == id); if (student == null) { return NotFound(); } ViewModel model = new ViewModel(); model.Student = student; return View(model); } edit.cshtml@model namespace.ViewModel

然后,在您Post方法上,您还应该使用ViewModel代替Bind

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, ViewModel model)
{
   (...)
}