I'm trying to follow best practices to add data validation to my UI. I want to add the data validation to the ViewModel and then if that data is valid, submit the form to the controller. However, the data the controller receives is always null values. Any idea what I'm doing wrong? This whole MVVC architecture is confusing me. I had it working when I was submitting the form using the model but I can't get data validation on the model?
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> CreateResource(AddResourceViewModel model)
{
if (ModelState.IsValid)
{
await (//does something);
}
return View();
}
ModelView:
public class AddResourceViewModel
{
public string User { get; set; }
public string ResourceName { get; set; }
public int ResourceId { get; set; }
public string Model { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public decimal Amount { get; set; }
public int UnitId { get; set; }
public int PrimaryEsfId { get; set; }
public IEnumerable<string> Capabilities { get; set; }
public IEnumerable<int> AdditionalEsfs { get; set; }
public Resource Resource { get; set; }
}
Beginning of cshtml form:
@model erms.ViewModel.AddResourceViewModel
<form asp-controller="AddResource" asp-action="NewResource" method="post" class="form-horizontal">
<div class="panel panel-default">
<div class="panel-body">
<form asp-controller="AddResource" asp-action="CreateResource" method="post" class="form-horizontal">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="ResourceId" class="col-md-2 control-label">Resource ID:</label>
<div class="col-md-10">
<input asp-for="ResourceId" class="form-control" value="@Model.Resource.ResourceId" readonly />
<span asp-validation-for="ResourceId" class="text-danger"></span>
</div>
</div>