0

I've tried to follow the answer by Darin Dimitrov on this post: How to create controls dynamically in MVC 3 based on an XML file. But in ASP .NET Core (Specifically ASP .NET Core 2) there is no DefaultModelBinder so I have to modify the Custom Model Binder code in order to work with ASP .NET Core.

Actually my code is:

public class ControlModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var type = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Type");
        object model = null;

        switch (type.FirstValue)
        {
            case "TextBox":
            {
                model = new TextBoxViewModel();
                break;
            }
            case "CheckBox":
            {
                model = new CheckBoxViewModel();
                break;
            }
            case "DropDownList":
            {
                model = new DropDownListViewModel();
                break;
            }
            default:
            {
                throw new NotImplementedException();
            }
        };

        bindingContext.ModelMetadata = ModelMetadataProvider.GetMetadataForType(model.GetType());
        bindingContext.Model = model;

        return Task.CompletedTask;
    }
}

The problem that I'm having actually is that ModelMetadataProvider.GetMetadataForType is showing me the error:

It's required a reference for a non-static field, method or property 'ModelMetadataProviderGetMetadataForType(Type)'.

So, What can I do in order to make work the model.GetType()?

How I can get ControllerContext and modelType?

If someone knows how to convert this piece of code from ASP .NET MVC to ASP .NET Core I would really apreciate his help.

Thank you in advance!

2
  • Don't you need to create a new instance of your model instead of setting it to NULL? Commented Aug 14, 2018 at 10:24
  • In MVC 5, you can use System.Web.Mvc.ModelMetadataProviders.Current.GetMetadataForType(), not sure if this works in .net core. Commented Aug 14, 2018 at 12:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.