Wiring a complex object (with hierarchy) to a controller in ASP.NET MVC

We use a strongly typed view to show a complex object in the form of data entry / editing. for example: Model.UserInformation.Name, Model.LivingPlace.FacilitiesSelectList, Model.Education.DegreesList ... etc. This data is displayed in a multihomed list, grids, etc. The user can change the information on the edit screen. Is there a way to post the model object with custom changes to the controller when the sumbit button is pressed. Please suggest.

Best regards, SHAN

+2


source to share


2 answers


The same object instance that was passed to the view: None. ASP.NET MVC uses the default middleware to generate new action parameters from request values. For example, if you had the following action method:

public ActionMethod DoWork(User model)
{
    return View();
}

public class Address
{
    public string Street { get; set; }
}

public class User
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address[] Addresses { get; set; }
}

      

the binder will look in the query and try to bind the model values. In your view, you can:



<%= Html.TextBox("FirstName") %>
<%= Html.TextBox("LastName") %>
<%= Html.TextBox("Addresses[0].Street") %>
<%= Html.TextBox("Addresses[1].Street") %>

      

This will automatically fill in the values โ€‹โ€‹of your model in the controller action.

To avoid bulk assigning properties that should not be bound from query values, it is always recommended to use BindAttribute and set the Exclude or Include properties.

+2


source


Use <input type="text" name="UserInformation.Name"><input>

to bind to sub-objects.



0


source







All Articles