1

I am getting a Null reference Exception when I am trying to access from my View to a Model property.

My View is:

@page
@model WebApp.Pages.IndexModel
<p id="token" style="visibility: hidden;">@Model.Token</p>

My Model is:

public class IndexModel : PageModel
{
    private string token = "token";

    public string Token{ get { return token; } }

    public IndexModel(string token)
    {
        this.token = token;
    }
}

And my Controller is:

public class PopUpAuthController : Controller
{
    public PopUpAuthController()
    {
    }

    public IActionResult Index()
    {
        return View(new IndexModel("TokenPlaceholder"));
    }
}

The @Model.Token is throwing me the exception. I tried to use DataView["Token"] for setting and getting but it throws the same exception.

I have very very simple code but I cant get with this error. I hope you can help me folks.

13
  • 2
    Are you sure token has a value? Have you debugged the controller method to see if it does? Commented Aug 16, 2019 at 9:17
  • 2
    Possible duplicate of What is a NullReferenceException, and how do I fix it? Commented Aug 16, 2019 at 9:18
  • Yes, I debugged it and it has a value at the moment of calling the View constructor.. It very strange Commented Aug 16, 2019 at 9:21
  • 4
    I am confused. You use a controller but have @page declared? What are you using now? MVC or Razor pages (which don't use controllers)? Razor pages are indepdendent of controllers and (unlike the name suggests) not (data transfer or view) models. When using a controller and an action named "Index" you need a Views/PopUpAuth/Index.cshtml to render your view. Or you just use Razor pages and put your logic in the IndexModel and trash your controller. Not both Commented Aug 16, 2019 at 9:35
  • 1
    You have to decide for one technology (Razor or MVC) and use that. You can mix both in the same application (iirc), but either RazorPages + Loginc inside XxxModel class or MVC with Controller + corresponding view. Commented Aug 16, 2019 at 9:41

1 Answer 1

2

Seems you are mixing razor pages (with @page declaration) and MVC here.

You should use only one per page, either regular cshtml Razor view (placed in folder named Views/PopUpAuth/Index.cshtml) and use a regular POCO model (no inheritance from PageModel).

Alternatively you just use razor view and put in your logic in the PopUpAuthModel's OnGet method and delete your controller.

You can use both in the same project, but you can't mix them on the same endpoint/route/page.

Sign up to request clarification or add additional context in comments.

Comments

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.