cori
cori

Reputation: 8810

Passing strongly-typed data from a View to a Controller

I've got a stringly-type view defined using @model MyNamespace.Customer with a form created using Html.BeginForm( "NewCustomer", "CustomerReg", FormMethod.Post ) helper.

The NewCustomer action on my CustomerRegController controller looks like

[HttpPost]
public ViewResult NewCustomer( MyNamespace.Customer objCustomer )

I am "filling" from model-bound fields on the page a portion of the Customer fields.

When I submit I get into the correct action, but the objCustomer is all initial values. I though I could pass strongly-typed data that way; am I doing something wrong?

Upvotes: 2

Views: 385

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

The fact that your view is strongly typed to @model MyNamespace.Customer doesn't mean that this model will somehow be automagically posted to your action when the form is submitted. Basically you need to have input fields for each property you want to retrieve inside your form if you want this property to be passed to your POST action.

Also make sure that this Customer object is a POCO with a default (parameterless) constructor where each property you would like to retrieve has public getters and setters. Otherwise the default model binder will never be able to deserialize the request to this model. The ideal solution to this problem is to use a view model which is a class that you specifically design to meet the requirements of your view and stop passing your domain models to it. This view model will of course have a default constructor and public setters and getters for all properties you would like to retrieve.

Upvotes: 1

Related Questions