1
votes

In ASP.NET MVC, on [HttpPost] methods, the MVC runtime will automatically maps and transfers the data from the form fields in the front end into a View Model, based on field names.

How can I accomplish the same thing in ASP.NET WebForm?

e.g. I have an object called Person with FirstName and LastName properties.

I have a WebForm page with Textbox controls with FirstName and LastName respectively.

When pressing Submit on the form, is there a way to automatically bind FirstName and LastName to the Person object in the code-behind Button_Click event?

4

4 Answers

5
votes

ASP.net 4.5 is actually going to have built in Web Forms model binding.

The Gu has a post on it and a few other things here...

http://weblogs.asp.net/scottgu/archive/2011/09/05/web-forms-model-binding-part-1-selecting-data-asp-net-vnext-series.aspx

4
votes

You can do this in webforms v4.5 using model binding. It's a way we call as Ad-Hoc Model Binding where you can bind to controls without using data bound controls such as formview. I plan to blog about it but following code describes the blog in short

The following is how your markup will look. My model has 2 properties: name and description

Name<input type="text" name="Name" value=" " id="Name"      />   
<br />

Description<input type="text" name="Description" value=" " id="Description"    />
<br />
<asp:Button Text="Submit" runat="server" OnClick="Unnamed_Click" />

The following is the code in the button click handler. category is my model. In this case the model binding system pulls in the value from the form value provider which looks in the form collection.

var category = new Category();
var formValueProvider = new FormValueProvider(ModelBindingExecutionContext);            

TryUpdateModel(category, formValueProvider);

if (ModelState.IsValid)
{
     // save changes to database
}
0
votes

Perhaps the easiest way is to assign the values explicitly in the Page_Load event, whenever it is a postback. Something like this:

if (this.IsPostBack)
{
    person.FirstName = FirstNameTextBox.Text;
    person.LastName = LastNameTextBox.Text;
}

Or were you looking for a more declarative approach?

0
votes

Take a look at Model Binder for ASP.NET Web Forms. It is doing what you want - maps postback data to class via custom attributes applied to its properties.