I'm building a ASP.NET MVC web application that has several forms in a view. I want the user to be able to fill out each form and capture the data for processing. These forms have a unique model, 3 for this page, that need to be added to the view somehow, so I have tried 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; }
}
All the models in the ViewModel look similar:
public class ConModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
. . .
}
I load ViewModel into my view in the controller:
public class FormsController : Controller
{
public IActionResult Index()
{
ViewModelFraud viewModelFraud = new ViewModelFraud();
viewModelFraud.ConModel = new ConModel();
viewModelFraud.CompanyModel = new CompanyModel();
. . .
return View(viewModelFraud);
}
}
In my view, I create a tag helper in my form:
<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>
. . .
I'm using asp-for="FirstName"
tag helper to get a label added to this input element from the model, but I get build errors if I try. The error implies that the tag helper doesn't see the model. Am I loading them incorrectly or at all?
Thanks, @pinkfloydx33 and @Farhad Zamani!
Turns out, you need to include the ViewModel into the view like so:
@model WebApp.Models.Con.ViewModel;
And asp-for="ConModel.FirstName"