Reputation:
I'm a beginner in ASP.NET Core MVC, just a question on Get/Post action methods, below is the code of a controller:
public class CheckoutController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(UserBindingModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction(nameof(Success));
}
public IActionResult Success()
{
return View();
}
}
we can see that for post method, a view model is passed to the Index view while it is not the case for get method. But the Index view is the same for both get and post as below:
@model UserBindingModel
@{
ViewData["Title"] = "Checkout";
}
...
...
...
so when using the get method, no model is passed to the view, but there is a @model directive at the top of the view template, so shouldn't it cause an null reference error?
Upvotes: 0
Views: 328
Reputation: 27538
The @model UserBindingModel
tells the Razor engine that the type of the model is UserBindingModel
, it declares the variable Model as UserBindingModel
type :
UserBindingModel Model;
so that when you use the keyword Model
, it will refer to the model you have defined :
@Model.ID
As it just declares the variable Model , it won't case error , but when you output the variables/properties of UserBindingModel
(for example, @Model.ID) which haven't been initialized and passed from controller , you will get error : NullReferenceException: Object reference not set to an instance of an object.
Upvotes: 1