jw56578
jw56578

Reputation: 399

MVC How to handle valid null model binding

Is there any generally accepted way to handle the following scenario or have I designed it poorly?

I have some domain models as such:

            public class Person
            {
                public int ID {get;set;}
                public string Name{get;set;}
                public int? AddressID {get;set;}
            }
            public class Address
            {
                public int ID{get;set;}
                public string Street {get;set;}
            }

Then I have a View Model as such:

            public class Personnel
            {
                public Person Person{get;set;}
                public Address Address{get;set;}
            }

So then i have a strongly typed view to the Personnel model and say I have something in it like this

            @Html.HiddenFor(m => m.Address.ID)
            @Html.EditorFor(m => m.Address.Street)

The thing is that when i get my Personnel model, sometimes Address can be null because sometimes a Person doesn't have an address. BUT the UI requires that the input text boxes still be shown. When Address is null, the resulting markup from the view is as such:

            <input value name="Address.AddressID" type="hidden">

I have a controller as such

    [HttpPost]
    public ActionResult EditPersonnel(Personnel model)
    {
        if (ModelState.IsValid)
        {
            model.Save() // or whatever
        }

        return View(model);

    }

So when I post back to my controller the value in the form collection for Address.ID has an empty string. The ModelState is always invalid because the binder cannot convert an empty string into an int. But I didn't want it to bind anyways because there really isn't any address ( lets say the user didn't enter any information). How do you get the binder to ignore the Address fields?

Upvotes: 1

Views: 2417

Answers (2)

Tieson T.
Tieson T.

Reputation: 21191

Realistically, the Address property should never be null if the view requires the model property. If the Person.AddressID is null, assign a "empty" instance of an Address to the Personnel.Address property:

// assuming you have a data object named "person"
if(!person.AddressID.HasValue) // or use person.AddressID == null
{
     model.Address = new Address(); // assuming your view model is called "model"
}

Upvotes: 1

Antarr Byrd
Antarr Byrd

Reputation: 26061

try

        [HttpPost]
        public ActionResult EditPersonnel(Personnel model)
        {
            if(model.Address.Equals(null))
              model.Address = new Address();
            if (ModelState.IsValid)
            {
                model.Save() // or whatever
            }

            return View(model);

        }

Upvotes: 0

Related Questions