3

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.

Second Person Shooter
  • 14,188
  • 21
  • 90
  • 165
  • 1
    The model will only be `null` if there are other errors with you code –  Oct 04 '17 at 08:40
  • @StephenMuecke: So is it necessary to always do double check as shown in my code above? Or `ModelState.IsValid=true` does not guarantee that `model != null`? – Second Person Shooter Oct 04 '17 at 08:44
  • It's generally be a good idea to check for `null` anyway. Hypothetically, it shouldn't be `null`, all going well but a refactor or other misconfiguration (e.g., routing), could cause it to be `null`. – DiskJunky Oct 04 '17 at 08:46
  • 1
    Actually, ModelState.IsValid checks if any errors is added to the ModelState, so in the case where model is nullable, ModelState is valid even if model is null. In your case however, BlogViewModel is required in your post request, so a request with a null model will raise exception instead. Therefore, you do not need to check if model is null in this case. – Daniel H.J. Oct 04 '17 at 08:46
  • 1
    `ModelState` is valid of the model is `null` (its only invalid if the `ModelBinder` attempts to set the value of property which is not valid). The model will be `null` if no values are passed in the request which match a model property name, or if you name the parameter the same as one of the properties in the model. –  Oct 04 '17 at 08:57
  • 1
    Personally I don't think its necessary (and have never seen any example of it). In the 2nd case above, you will have corrected that before publishing, and if no values matching your model properties were sent in the request, you can assume its a malicious user and so what if they see the error page that will result from the exception. –  Oct 04 '17 at 09:16

3 Answers3

3

To answer your question, no, ModelState.IsValid does not check if your model is null and will throw an error if that happens.

In an API it is quite easy to have null models, if you make a mistake while building your request model and it doesn't match what the endpoint expects.

Or someone else could look at your website, see the API calls and decides to have some fun and flood your API with requests which don't have valid models.

There are ways to check for null models in one place such as here : ModelState is valid with null model

Andrei Dragotoniu
  • 6,155
  • 3
  • 18
  • 32
1

what is Model State ? The ModelState represents a collection of name and value pairs that were submitted to the server during a POST

What's in a ModelState? Here's what those values look like, from the same debugger session: enter image description here Each of the properties has an instance of ValueProviderResult that contains the actual values submitted to the server.

Validation errors in Model State... eg:-

[Required]
public string FirstName { get; set; }

[StringLength(50, ErrorMessage = "The Last Name must be less than {1} characters.")]
public string LastName { get; set; }

in this case if your LastName contain more than 50 caracters, ModelState if false, because vaueProvidedResult having exception

Hope you got the understating about ModelState

Answer for your question is you can handle model from modelState

if model null automatically modelState is not valid

1

The answer is simply no.

ModelState represents attempts to bind a posted form (marked with BeginForm) to an action method which also includes validation information. It carries default model binder settings that specify which validation settings should be included to viewmodel, e.g. RequiredAttribute, so that null-value checking for required fields depend on which validation settings exist, not in ModelStateDictionary itself.

When the form is submitted, the DefaultModelBinder sets up viewmodel binding and checks every properties inside bound viewmodel class for presence of validation settings (i.e. attributes). If submitted values doesn't match with criteria being set (e.g. null/empty value in properties marked with RequiredAttribute), it will add validation error(s) to ModelState.Errors property, and subsequently ModelStateDictionary.IsValid returns false because it depends on Errors property count. Here is IsValid checking mechanism taken from ModelStateDictionary source:

public class ModelStateDictionary : IDictionary<string, ModelState>
{
    private readonly IDictionary<string, ModelState> _innerDictionary;

    public ICollection<ModelState> Values
    {
        get { return _innerDictionary.Values; }
    }

    public bool IsValid
    {
        get { return Values.All(modelState => modelState.Errors.Count == 0); 
    }
}

Hence, if all model properties set to null/empty without specifying RequiredAttribute, the ModelStateDictionary.IsValid value still being true due to no validation attributes present & the model binding works.

Similar issue:

ModelState.IsValid even when it should not be?

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61