views:

352

answers:

1

ASP.NET MVC 2.0: Simple Model Binding not working/binding as it should

i have a simple custom object names Comment (linq to sql generated one), it has various values, but only two values are being sent from a HTML POST from to my action, and here is my action that accepts them...

 Function InsertComment(ByVal Comment As Comment) As ActionResult  
              ' both CommentForPicID As Integer and Comment As String are the two values sent.

 End Function

The textarea is named using the TextAreaFor and the hidden id with HiddenFor, and i have checked to make sure the property names of my Comment object match exactly (case and all) with the HTML ID/Name values of the FORM elements, both are CommentForPicID and Comment without any prefixes.

i have a breakpoint on my action to see whats going on, When my action receives it, the Comment object is always set to Nothing, throughout the action, and eventually an exception is thrown as i'm trying to use a null object.

i have read steven sandersons MVC framework's model binding section, everything should be in order, does anyone have any ideas?

. . .

Additional information (reading not required): however the interesting thing is, if i wrap the Comment object up in a parent object, say, CommentsParent with contains some stuff & the Comment object as variables... then i of course change the form elements id's with the apporpriate prefixes, it then works as prescribed... but i did this just to test that binding was working, and dont want/need to do this for my application.

here is the markup for anyone who wants to see it:

<%@ Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl(Of FP.Comment)" %>

<%@ Import Namespace="FP" %>

<%--The line below is a workaround for a VB / ASPX designer bug--%>
<%=""%>
<% Html.EnableClientValidation()%>

<% Using Ajax.BeginForm("InsertComment", "Home", New AjaxOptions With {.UpdateTargetId = "InsertComment", .HttpMethod = FormMethod.Post})%>

   <%= Html.HiddenFor(Function(x) x.CommentForPicID)%>

   <%= Html.TextAreaFor(Function(x) x.Comment, 8, 40, New With {.style = "overflow: hidden;"})%><br />

   <%= Html.ValidationMessageFor(Function(x) x.Comment)%>


  <input type="submit" value="Save" name="SaveCancelButton"/>
  <input type="submit" value="Cancel" name="SaveCancelButton" />

<% End Using %>
+3  A: 

The problem is that your model class is named Comment and inside you have a string property also called Comment that you try to bind to the textarea. This doesn't work as the binder is getting confused. Either use a bind prefix or rename the property or the class so that they are different.

Darin Dimitrov
thank you so much! you were completely right! it was a naming issue! i have since renamed my Comment string to UserComment and everything works as expected!
Erx_VB.NExT.Coder