I have a controller with 4 post methods all with the same name but with different parameter types as follows. (Please note I am just testing here, so ignore the body of each method and the fact that I am not using ValidateAntiForgeryToken yet.)
[HttpPost]
public IActionResult CreateHealthCheck(FileHealthCheckOptions model)
{
var json = JsonConvert.SerializeObject(model);
return View("Index");
}
[HttpPost]
public IActionResult CreateHealthCheck(HTTPHealthCheckOptions model)
{
var json = JsonConvert.SerializeObject(model);
return View("Index");
}
[HttpPost]
public IActionResult CreateHealthCheck(PingHealthCheckOptions model)
{
var json = JsonConvert.SerializeObject(model);
return View("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CreateHealthCheck(SqlServerHealthCheckOptions model)
{
var json = JsonConvert.SerializeObject(model);
return View("Index");
}
My View includes the following
@using ADLK.AppManager.Domain.Models.HealthChecks
@model ADLK.AppManager.Domain.Interfaces.IHealthCheckOptions
@section Scripts
{
<script src="~/js/app/health/createhealthcheck.js"></script>
}
<h4>Create Health Check</h4>
@{
ViewBag.Title = "Application Manager - Test";
var modelType = $"{Model.GetType().Name}".Replace("Options", "");
}
<input type="hidden" id="healthchecktype"/>
<select id="healthcheckselect" class="form-select-sm mt-2">
@foreach (var item in ViewBag.AvailableHealthChecks)
{
var selected = (modelType == item);
<option class="small" selected="@selected" value="@item">@item</option>
}
</select>
<div class="row">
<form asp-action="CreateHealthCheck">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-4 mt-4">
<label asp-for="@Model.Name"></label>
<input asp-for="@Model.Name" autocomplete="off" class="form-control" />
<span asp-validation-for="@Model.Name" class="text-danger"></span>
</div>
. . . . .
When I submit my view, I get the error '
The request matched multiple endpoints
Perhaps there's a way to route based on the parameters? I don't know. I'd like to keep the post method name the same so that my view is clean if possible.
Each HealthCheckOptions class, is based on an IHealthCheckOptions interface. I tried setting up a single post method thus
[HttpPost]
public IActionResult CreateHealthCheck(IHealthCheckOptions model)
{
var json = JsonConvert.SerializeObject(model);
return View("Index");
}
but when I submit to that from my view, I get the error
Could not create an instance of type '...'. Model bound complex types must not be abstract or value types and must have a parameterless constructor
Is there a better way to do this? I'd like to implement a solution whereby I could add various new HealthCheckOptions in the future and have the Asp.Net app work for these without having to change the view. Any help greatly appreciated.