Assume that we have Create
and Edit
action methods that are attributed by HttpPost
and they have a model
parameter of type, for example, BlogViewModel
as follows.
[HttpPost]
public IActionResult Create(..., BlogViewModel model)
{
....
}
[HttpPost]
public IActionResult Edit(..., BlogViewModel model)
{
....
}
In their body, we usually do validation as follows.
if(ModelState.IsValid)
{
// do something
}
Here, do something
can be an operation accessing a property of the model
.
Question
I am not sure whether or not there is a possibility in which model
becomes null
. If model
is null
then do something
(such as accessing a property of model
) will throw an exception.
I read many examples (from the internet and textbooks), I have not seen someone doing double check as follows yet.
if(model!=null)
{
if(ModelState.IsValid)
{
// do something
}
}
or
if(ModelState.IsValid)
{
if(model!=null)
{
// do something
}
}
Probably, the condition ModelState.IsValid
is true
guarantees that model
is not null
.
Is my assumption here correct? I am afraid I am doing a time-bomb assumption.