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?

1 Answer 1

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;}
}
Sign up to request clarification or add additional context in comments.

2 Comments

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 (stackoverflow.com/questions/7208911/…). 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.
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.