How can I fix this issue System.MissingMethodException: 'No parameterless constructor defined for this object.'
I followed this code from codeproject CodeProject Code .
Already tried adding blank constructor in Controller but it's giving me another error. InvalidOperationException: Multiple constructors accepting all given argument types have been found in type 'SlhSd18.Controllers.FunctionsController'. There should only be one applicable constructor.
Here is my model code:
namespace SlhSd18.Models
{
public class Function
{
public int Id { get; set; }
[Required, StringLength(10)]
[CustomRemoteValidation("IsFunctionIdExist", "Functions", AdditionalFields = "Id",
ErrorMessage = "Function Id already exist.")]
public string FunctionId { get; set; }
Controller Code:
namespace SlhSd18.Controllers
{
public class FunctionsController : Controller
{
private readonly SlhSd18Context _context;
public FunctionsController(SlhSd18Context context)
{
_context = context;
}
public IActionResult IsFunctionIdExist(string functionId, int ? Id)
{
bool validate = _context.Function.Any
(x => x.FunctionId == functionId && x.Id != Id);
if (validate ==true)
{
return Json(false);
}
else
{
return Json(true);
}
}
SlhSd18 Class Code
namespace SlhSd18.Models
{
public class SlhSd18Context : DbContext
{
public SlhSd18Context (DbContextOptions<SlhSd18Context> options)
: base(options)
{
}
public DbSet<SlhSd18.Models.Movie> Movie { get; set; }
public DbSet<SlhSd18.Models.ChartofAccount> ChartofAccount { get; set; }
public DbSet<SlhSd18.Models.Function> Function { get; set; }
}
}
I don't know setup of your DI, but I suggest to use this method to create controller instance:
private object TryCreateController(ValidationContext context, string controllerName) {
Type controllerType = Assembly.GetExecutingAssembly().GetTypes().Single(x => x.Name.ToString().ToLower() == controllerName+"Controller");
if (controllerType == null) {
return null;
}
foreach (var constructor in controllerType.GetConstructors()) {
var parameters = constructor.GetParameters();
var args = new dynamic[parameters.Length];
for (int i = 0; i < parameters.Length; i++) {
args[i] = context.GetService(parameters[i].ParameterType);
}
try {
var instance = Activator.CreateInstance(controllerType, args);
if (instance != null) {
return instance;
}
}
catch {
continue;
}
}
return null;
}
And you can change the highlighted line to the next:
object instance = TryCreateController(validationContext, this.RouteData["controller"].ToString().ToLower());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.