0

The problem is the UserTypes property (used to populate a drop down list in the AddUser view) is not being retained after POSTback of the form.

Here is my AddUserModel: (which inherits from EditUserModel which doesn't have properties for UserTypes/UserTypesSelectList - probably part of the problem?)

 public class AddUserModel : EditUserModel
    {
        public AddUserModel() : this(new Dictionary<string, string>())
        { 
        }

        public AddUserModel(Dictionary<string,string> userTypes)
        {
            UserTypes= userTypes;
        }

        //properties etc

        public Dictionary<string, string> UserTypes{ get; private set; }

        public SelectList UserTypesList
        {
            get { return new SelectList(UserTypes, "key", "value"); }
        }
}

The view has the following but it calls the parameterless constructor in the above code first instead of the AddUser() method in the controller:

   using (Html.BeginForm<MyController>(c => c.AddUser(Model)

I can see when debugging that this is because the parameterless constructor method in the AddUserModel is being called first instead of the controller method being called (thereby instantiating an empty AddUserModel). I found this question on this site but I still do not understand.

Debugging shows that after POSTback of the form the AddUserModel contains no data, but the EditUserModel does contain the data (except the UserTypes data because it doesn't have a property for that)

Should both the Add and Edit Models have the same properties? i.e UserTypes and UserTypesSelectList? Is there something I'm missing in terms of how Models inherit from each other and relate to Views?

Edit

After abit of research and deciding to use a shared model I was able to fix the above. Please refer to my answer for more details.

0

I solved this problem by making a shared model for both AddUser and EditUser rather than having two separate models with AddUserModel inheriting from EditUserModel. When submitting the form in the view the default/parameterless constructor is always called and that is the expected behaviour of MVC and not an error as I first suspected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.