views:

29

answers:

1

Hi All,

I used Visual Web Developer 2010 and ASP .NET with MVC2 to create a simple Customer Management module, where the view will allow entering first name, last name, address, etc., and upon submitting, a new "ID" will be assigned to the CustomerID property of the CustomerModel instance.

The Controller method (CustomerController) for creating customer is as below:

<HttpPost()> _
Public Function CreateCustomer(ByVal model As CustomerModel) As ActionResult
    model = Me.customerServiceClientValue.CreateCustomer(model)
    Return (View(model))
End Function

I can see that the control reaches inside the CreateCustomer () method, and it calls the Customer Service to create the customer. The service returns a customer with a new ID as well. As in the method, the customer instance returned from the service call is assigned back to the "model" variable that came in. That model instance is passed to the "View" in the return statement. Yet, when the view is refreshed, I do not see a value for the customer ID field.

I have the following mark-up for the customer ID field:

<div class="editor-label">
    <%: Html.LabelFor(Function(model) model.CustomerID)%>
</div>
<div class="editor-field">
    <%: Html.TextBoxFor(Function(model) model.CustomerID)%>
    <%: Html.ValidationMessageFor(Function(model) model.CustomerID)%>
</div>

What am I doing wrong? Why am I not getting the Customer ID in the field, although the model contains the new Customer ID? Appreciate all your helps.

Thanks and regards,

Dinesh Jayadevan

A: 

Because TextBoxFor (and other helpers) always looks at the post values first to display. If no post value exists then it looks at the model. The reason for this is because if your form has errors your generally want your form to show the same data as was posted rather than some, possibly altered, model data.

You can call ModelState.Clear(); in your controller to prevent that but it's not a good idea.

More info on this http://blogs.msdn.com/b/simonince/archive/2010/05/05/asp-net-mvc-s-html-helpers-render-the-wrong-value.aspx

BuildStarted