Lys
Lys

Reputation: 631

Accessing model from razor view in MVC

I have the following code in controller and razor view.

When Upload() is called I want to return another view with the model as the parameter so it's accessible within the view.

But I keep getting "Object reference not set to an instance of an object" on @Model.PhoneNumber

Another question is that does the model has to be strongly typed? It seems when I pass in new { PhoneNumber = "123456" } the property can't be accessed from view either.

[HttpGet]
[Route("{code}/CertificateValidation")]
public ActionResult CertificateValidation()
{
    return View();
}

[HttpPost]
public ActionResult Upload(FormCollection file)
{
    return View("CertificateValidation", new IndexViewModel { PhoneNumber = "123456" });
}

View:

model WebApplicationMVC.Models.IndexViewModel    
<p>@Model.PhoneNumber </p>

Upvotes: 1

Views: 953

Answers (2)

dotnetstep
dotnetstep

Reputation: 17485

Problem is with your get Method.

Your following method does not return any model. So Model is null so it gives error.

[HttpGet]
[Route("{code}/CertificateValidation")]
public ActionResult CertificateValidation()
{
    var model = new IndexViewModel();
    return View(model);
}

Upvotes: 1

bilal.haider
bilal.haider

Reputation: 318

The way you are returning the view with the model is correct and should not have any issue.

return View("CertificateValidation", new IndexViewModel { PhoneNumber = "123456" });

That said, most probably your actual code would not be like this and might be fetching data from some source like a database probable, which could be returning null which you can investigate by debugging or writing null checks.

For the second answer, if you are specifying the type of the model in the view with the @model directive, you have to provide an instance of this type in the return View() method call. Alternatively you can use the @model dynamic which would allow you to pass anything as the model. See this link

Upvotes: 0

Related Questions