aeliusd
aeliusd

Reputation: 469

ASP.Net MVC Model binding for empty input string creates empty model object

I've been trying to get my head around how to solve this problem in the cleanest way.

How to get the model binder to NOT create empty objects when submitting empty strings for complex types?

Say I've got this model:

public class CreateCaseModel
{
    [Required]
    public UserModel Contact { get; set; }

    public UserModel Assigned {get; set; }
}

and the user-model:

public class UserModel {
    [Required]
    public string Id {get;set;}

    public string Name {get;set;
}

And in the view i have these inputs:

<input type="hidden" name="Assigned.Id" value="" />
<input type="hidden" name="Contact.Id" value="userId1" />

I post this to a controller something like:

public ActionResult Create(CreateCaseModel model){
    if (!ModelState.IsValid)
    {
        //handle error       
    }else {
        //create
    }
}

In the controller now my model.Contact and model.Assigned will never be null. Only the model.Contact will however contain anything (the Idwill be set) At this point the modelstate will also be invalid due to the fact that the UserModel.Id field is marked as required.

What I want to happen is for the binder to not create the UserModel object at all if the input is empty.

The entire reason for me needing this is that I'm using the UserModel.Name field elsewhere in the view, and I'd like to group the two fields together. And I want to use the ModelState.IsValidcheck for serverside validation.

I could of course go with extracting the Id and Name fields of each userobjects and put them directly in the CreateCaseModel, but I want to explore if what I describe is even possible.

Grateful for any tips or pointers!

Upvotes: 2

Views: 1188

Answers (1)

Erik Philips
Erik Philips

Reputation: 54676

How to get the model binder to NOT create empty objects when submitting empty strings for complex types?

Write your own custom ModelBinder. The default model binder will always attempt to create complex types for recursive modelbinding.

Upvotes: 2

Related Questions