Home > OS >  How to create an ASP.NET Core ViewResult in a class library?
How to create an ASP.NET Core ViewResult in a class library?

Time:06-23

In my ASP.NET Core website, I have a class library which does some boring logic but finally returns either:

  • new RedirectResult("-some url");
  • new ViewResult(....)

now I'm not sure how I can pass a model to the ViewResult?

I tried this:

var viewResult = new ViewResult
{
    ViewName = "MarketingPreferences",
};

viewResult.ViewData.Model = myModel; // Exception is thrown :(

but the viewData property is null.

So then I thought: just create it, right?

viewResult.ViewData = new ViewDataDictionary(..) but I don't know what to pass into that :(

There are the two options:

  • public ViewDataDictionary(ViewDataDictionary source);
  • public ViewDataDictionary(IModelMetadataProvider metadataProvider, ModelStateDictionary modelState);

and I don't have an existing ViewDataDictionary in the first option ...

and for the second .. i have no idea what an IModelMetadataProvider is?

Can anyone help, please?

CodePudding user response:

If you want to pass model to the ViewResult, You can follow this code:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

public class Test
    {
        Stu stu = new Stu()
        {
            Name = "Jack"
        };


        public ViewResult test()
        {
            var viewData = new ViewDataDictionary<Stu>(new EmptyModelMetadataProvider(), new ModelStateDictionary());
            viewData = new ViewDataDictionary<Stu>(viewData, stu);

            ViewResult viewresult = new ViewResult()
            {
                ViewData = viewData
            };


            return viewresult;
        }
    }
  • Related