简体   繁体   中英

Passing data into an Asp.Net Core bound model

I have an Asp.Net Core 2 project, whereby I'm trying to change the data in a class from a form; here's my form:

@model MyProject.Model
@{
    ViewData["Title"] = " ...";
}
. . . 
    <form asp-action="MyMethod" asp-controller="MyController">
        <input type="text" asp-for="MyClass.MyValue" />

    </form>

The referenced model looks like this:

public class Model
{
    public MyClass MyClass { get; set; }

    public Model(MyClass myClass)
    {
        MyClass = myClass
    }

The idea being that MyClass gets registered with the IoC initially, and its current value gets passed into the web page. The user can then change the values and post it on to MyController . The controller looks like this:

public class MyController : Controller
{
    [HttpPost]
    public async Task<IActionResult> MyMethod(Model myModel)
    {

However, when I execute this and call MyMethod , I get the error:

InvalidOperationException: Could not create an instance of type 'Model'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the 'myModel' parameter a non-null default value.

Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)

So, it appears from the error that what I'm trying to do is explicitly prohibited by Asp.Net Core. I'm curious as to why that is the case (since it has the object in the IoC), but this is presumably well trodden ground, so how can I pass this class in?

EDIT:

The class is registered in Startup.cs using the Asp.Net core IoC container:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<MyClass, MyClass>();

You Need to update model as below. You need to create default constructor as when we post complex model because during model binding engine can't identify with parameter constructor.

public class Model
{
    public MyClass MyClass { get; set; }
    public Model()
    {
        //MyClass = myClass;
    }
    public Model(MyClass myClass)
    {
        MyClass = myClass;
    }
}

My action method

[HttpPost]
public async Task<IActionResult> MyMethod(Model myModel)
{
   //return View();
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM