As a newcomer to web design using ASP.NET Core, I have created a view component that contains a form with various inputs related to a specific view model. One of these inputs happens to be a file input of the IFormFile datatype.
My goal is to submit this view model to a controller's POST action, validate the model's state, return another view component if the model is valid, and remain on the current view component with the same view model if the model is deemed invalid.
Here is the View Model I am working with: PricingViewModel.cs
public class PricingViewModel
{
[Display(Name = "Select a file")]
public IFormFile formFile { get; set; }
[Display(Name = "ColumnCode")]
[Required(ErrorMessage = "Enter {0} value, please")]
public string colCode { get; set; }
[Display(Name = "ColumnName")]
[Required(ErrorMessage = "Enter {0} value, please")]
public string colName { get; set; }
}
The View Component (controller) being used: PricingComponent.cs
public class PricingComponent : ViewComponent
{
public async Task<IViewComponentResult> InvokeAsync(PricingViewModel pricing)
{
return await Task.FromResult((IViewComponentResult)View("PricingView", pricing));
}
}
The associated View Component (view): PricingView.cshtml
<form class="text-left" method="post" enctype="multipart/form-data">
<input name="IsValidPricing" type="hidden" value="@ViewBag.isValid" />
<div class="form-group text-left">
<label asp-for="colCode" class="control-label"></label>
<input asp-for="colCode" class="form-control" id="colCodeId"/>
<span asp-validation-for="colCode" class="text-danger"></span>
</div>
<div class="form-group text-left">
<label asp-for="colName" class="control-label"></label>
<input asp-for="colName" class="form-control" id="colNameId"/>
<span asp-validation-for="colName" class="text-danger"></span>
</div>
<div class="form-group text-left">
<label asp-for="formFile" class="control-label"></label>
<input type="file" accept=".xlsx, .csv" asp-for="formFile" id="MyInputFile"/>
</div>
<div class="form-group mt-4">
<input type="submit" asp-action="ShowPricing" asp-controller="Home" value="Show" id="ShowPricingBtn" />
</div>
</form>
The Home Controller in use: HomeController.cs
[HttpPost]
public IActionResult ShowPricing(PricingViewModel pricing)
{
//Validation logic and handling of submission results
}
Plan A
The primary approach mentioned above.
Problem
Issues faced while trying to handle model validation and staying on the same view component.
Plan B
An alternate plan involving AJAX for better validation management.
Modifications made to PricingView.cshtml to accommodate AJAX behavior.
Problem
New problems encountered when implementing AJAX for model submission.
I need help deciding between the original or alternative approach. Can you identify where I might be going wrong?