简体   繁体   中英

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);

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());

    ...

}

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