Anthony Sherratt
Anthony Sherratt

Reputation: 475

Best way to pass a model to a new ViewDataDictionary in MVC6

I'm trying to migrate my current MVC5 project over to MVC6 but have hit a minor snag around the new namespaces/methods, primarily with ViewDataDictionary. In MVC5 you could easily initiate a new ViewDataDictionary by just passing your model like so...

PartialViewResult pv = new PartialViewResult();
pv.ViewData = new ViewDataDictionary(model);

...but there doesn't seem to be any overloads for this in MVC6 without actually having a ViewDataDictionary object available.

So I suppose my question is, what is the best method to create a new ViewDataDictionary from scratch? I can see the following overload but I'm unable to find any examples on how to use it.

public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState);

Upvotes: 3

Views: 2841

Answers (1)

Daniel J.G.
Daniel J.G.

Reputation: 35042

You could create a new ViewDataDictionary and then assign its model property.

You will just need to get an IModelMetadataProvider which you can either get using DI in your controller or via the HttpContext.ApplicationServices service locator.

public IActionResult SomeAction()
{
    var modelMetadataProvider = this.Context.ApplicationServices.GetRequiredService<IModelMetadataProvider>();
    var viewDataDictionary = new ViewDataDictionary<FooModel>(modelMetadataProvider, new ModelStateDictionary());
    viewDataDictionary.Model = new FooModel();

    ...        

}

Maybe you could provide an extension method:

public static ViewDataDictionary<T> CreateViewDataDictionary<T>(this HttpContext httpContext, T model)
{
    var modelMetadataProvider = httpContext.ApplicationServices.GetRequiredService<IModelMetadataProvider>();
    return new ViewDataDictionary<T>(modelMetadataProvider, new ModelStateDictionary())
    {
        Model = model
    };
}

public IActionResult SomeAction()
{
    var viewDataDictionary = this.Context.CreateViewDataDictionary(new FooModel());

    ...

}

Upvotes: 5

Related Questions