1

In MVC3 Razor:

I am trying to create a form, dynamically, using fields from multiple objects. But for some reason the data I get in the controller doesn't contain the input values.

FormViewModel.cs

    namespace DynamicForm.Models
    {
        public class FormViewModel
        {
            public Name name = new Name();
            public Address address = new Address();

            public FormViewModel()
            {
            }
        }

public class Name
    {
        [Required()]
        public String first { get; set; }
        [Required()]
        public String last { get; set; }

        public Name()
        {
            first = "";
            last = "";
        }
    }
    public class Address
    {
        public String street1 { get; set; }
        public String street2 { get; set; }

        public Address()
        {
            street1 = "";
            street2 = "";
        }
    }

    }

FormController.cs

[HttpPost()]
        public ActionResult Save(FormViewModel toSave)
        {
            return View();
        }

index.cshtml:

@using DynamicForm;
@using DynamicForm.Models;
@model FormViewModel

@{
    ViewBag.Title = "Form";
}

<h2>Form</h2>

    @using (Html.BeginForm("Save", "Form"))
    { 
        @Html.TextBoxFor(m => m.address.street1)
        @Html.TextBoxFor(m => m.address.street2)

        @Html.TextBoxFor(m => m.name.first)
        @Html.TextBoxFor(m => m.name.last)

        <input type="submit" value="Send" /> 
    }

Any ideas as to why the data isn't being populated into the FormViewModel object?

KenEucker
  • 4,932
  • 5
  • 22
  • 28

1 Answers1

5

In your FormViewModel, name and address should be properties. The default model binder only works on properties.

public class FormViewModel
{
    public Name Name {get;set;}
    public Address Address {get;set;}
}
Community
  • 1
  • 1
RyanW
  • 5,338
  • 4
  • 46
  • 58
  • I made that change and it works, however now I have another issue. I created custom helpers in order to build form input controls and retain my data annotations and make a data driven form view. This fixed the issue for the controls if I use TextBoxFor, but not if I use my own helpers (http://stackoverflow.com/questions/7208911/dynamically-call-textboxfor-with-reflection). Any idea why using reflection here would lose my data? If I don't have the data nested and catch one of the objects directly it still works. IE: public ActionResult Save(Name toSave) gets the Name information with my helper. – KenEucker Aug 29 '11 at 19:58
  • I realize now why It's not working, and that's because my reflection doesn't go above the object I am passing it. What I am trying to accomplish just might be impossible... – KenEucker Aug 29 '11 at 20:11