当我有2个或更多模型时,最佳做法是什么?我想在表单中使用所有模型的属性?
namespace TestApplication.Models
{
public class Parent
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string HouseNumber { get; set; }
public string City { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
}
}
namespace TestApplication.Models
{
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Birthday { get; set; }
public int Grade { get; set; }
public char Class { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
}
}
===我需要将生成的ViewModel传递给FormController操作来处理表单。
===表单(cshtml文件)本身将包含两个类的所有属性的输入字段。我还想在表格中有两个以上的课程。
我应该使用AutoMapper并将两个/多个模型映射到一个ViewModel中吗? 如果是,那么最好的方法是什么?
我是否应该创建一个将Student和Parent类作为属性的公共FormClass?
还有其他/更好的方法吗?
答案 0 :(得分:0)
最好的方法是为类似的属性使用不同的名称。例如Email
Parent
使用ParentEmail
,Student
StudentEmail
使用{{1}}。
答案 1 :(得分:0)
由于您拥有表示层,因此我会使用#2来简化并快速生成/部署,并且我不必担心我发送给客户端的字段。如果这个应用程序是一个API,我将使用#1并使用Profile使用Automapper将视图模型映射到您的域类。
答案 2 :(得分:0)
为此我建议以下解决方案。我部分同意你的第二点。
模型应如下所示。
public class Parent
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string HouseNumber { get; set; }
public string City { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
}
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Birthday { get; set; }
public int Grade { get; set; }
public char Class { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
}
public class FormClass // This is what you suggested but it use other two model
{
public Student Student { get; set; }
public Parent Parent { get; set; }
}
视图应使用FormClass
@model HelloMvc.FormClass
<form method="post" action="/">
<div class="row">
<div class="col-md-4">
@Html.EditorFor(cc=>cc.Parent)
</div>
<div class="col-md-4">
@Html.EditorFor(cc=>cc.Student)
</div>
<div class="col-md-4">
<input type="submit" />
</div>
</div>
</form>
注意:
控制器应如下所示。
public class HomeController : Controller
{
[HttpGet("/")]
public IActionResult Index()
{
return View();
}
[HttpPost("/")]
public IActionResult Index(FormClass model)
{
return View(model);
}
}
答案 3 :(得分:-3)
asp.net mvc默认可以1模型发送到查看unlink php 有许多不同的方式 我认为ViewModel是最好的 但另一方面太难了:(
TestViewModel:
public list<db1> one { get; set; }
public list<db2> two { get; set; }
控制器:
var vm = new TestViewModel();
vm.one = db.db1.tolist();
vm.two = db.db2.tolist();
查看:
@foreach(var item in Model.one){
@foreach(var x in Model.two){}
}