使用 ViewModel 将多个模型添加到视图时如何使用标签助手?

How to use tag helpers when using ViewModel to add multiple models to a view?

我正在构建一个 ASP.NET MVC Web 应用程序,它在一个视图中有多个表单。我希望用户能够填写每张表格并捕获数据进行处理。这些表单有一个独特的模型,这个页面有 3 个,需要以某种方式添加到视图中,所以我尝试了 ViewModel。

ViewModel.cs

public class ViewModel
{
    public ConModel ConModel { get; set; }
    public CompanyModel CompanyModel { get; set; }
    public ComplaintModel ComplaintModel { get; set; }
    public KnowledgeModel KnowledgeModel { get; set; }
}

ViewModel 中的所有模型看起来都很相似:

public class ConModel
{
    [Required]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }
    . . .
}

我在控制器中将 ViewModel 加载到我的视图中:

public class FormsController : Controller
{
    public IActionResult Index()
    {
        ViewModelFraud viewModelFraud = new ViewModelFraud();
        viewModelFraud.ConModel = new ConModel();
        viewModelFraud.CompanyModel = new CompanyModel();
        . . .
        return View(viewModelFraud);
    }
}

在我看来,我在表单中创建了一个标签助手:

<form asp-page-handler="Con" method="post">
     <div class="col-sm-12">
         <div class="custom-control custom-switch">
              <input type="text" class="custom-control-input" id="FirstName">
              <label class="custom-control-label" asp-for="FirstName"></label>
         </div>
     </div>
     . . .

我正在使用 asp-for="FirstName" 标签助手从模型中获取添加到此输入元素的标签,但如果尝试,我会遇到构建错误。该错误意味着标签助手看不到模型。我是否加载错误或根本没有加载它们?

谢谢@pinkfloydx33 和@Farhad Zamani!

事实证明,您需要像这样将 ViewModel 包含到视图中:

  @model WebApp.Models.Con.ViewModel;

asp-for="ConModel.FirstName"