Home > Software engineering >  How can I create a ViewResult Object?
How can I create a ViewResult Object?

Time:04-11

The SDK I am using is .net 6.0.201

There are some situations in the controller that need to return a 404 page.

Currently, I achieve it like this:

Response.StatusCode = 404;
///log something
return View("/Views/Others/Error.cshtml", 404);

However, I need to add the codes above to all the positions needed to return a 404 page. It is not well to manage the code. So, I am about to move all of them into an inject dependency class then reference it:

public ViewResult ErrorView(HttpResponse Response)
        {
            Response.StatusCode = 404;
            ///log something
            return new ViewResult("/Views/Others/Error.cshtml", 404);
        }

Now, VS reports an error that:

CS1729:'ViewResult' does not contain a constructor that takes 2 arguments.

What's wrong with my code? Thank you.

CodePudding user response:

I think to create a ViewResult object, you need to give it a string and a ViewDataDictionary object. The 404 is an integer and not a ViewDataDictionary.

Maybe try to modify the code like so, let me know if this works:

        {
            Response.StatusCode = 404;
            ///log something
            return new ViewResult(
               ViewName: "/Views/Others/Error.cshtml",
               ViewData: 
                   new ViewDataDictionary(new EmptyModelMetadataProvider(),
                                          new ModelStateDictionary())
                   {
                       Model = 404 // If the view is expecting an integer, 
                                   // if it's not, supply it with the correct model.
                   }
               });
        }

CodePudding user response:

Change your code to:

public ViewResult ErrorView(HttpResponse Response)
{
    Response.StatusCode = 404;
    var res = new ViewResult()
    {
        StatusCode = 404,
        ViewName = "/Views/Others/Error.cshtml"
    };
    return res;
}
  • Related