collinszac10
collinszac10

Reputation: 198

Issue with the string value "Boolean" using HtmlHelper DisplayFor

I'm running in to an issue where I am trying to display values to the user by iterating an object and using HtmlHelpers. Currently one column will carry the data type of the items I writing to the screen and they are string values. I am running in to an issue when I try to render the value "Boolean", which is data type string, using the DisplayFor method. I am getting a FormatException saying "String was not recognized as a valid Boolean." I've tried casting it as a string several ways but to no luck. If I change the string from "Boolean" to anything else, it works just fine. Any suggestions?

<%foreach (var matrixColumnView in Model.MatrixColumns)
  {%>
<tr id="<%="ColRow_" + matrixColumnView.Key %>" class="columnRow">
    <td class="ui-helper-hidden">
        <%=Html.HiddenFor(x => x.MatrixColumns[matrixColumnView.Key].EntityId)%>
    </td>
    <td>
        <%=Html.HiddenFor(x => x.MatrixColumns[matrixColumnView.Key].Sequence)%>
        <%=Html.DisplayFor(x => x.MatrixColumns[matrixColumnView.Key].Sequence, matrixColumnView.Value.Sequence.ToString())%>
    </td>
    <td>
        <%=Html.HiddenFor(x => x.MatrixColumns[matrixColumnView.Key].Name)%>
        <%=Html.DisplayFor(x => x.MatrixColumns[matrixColumnView.Key].Name, matrixColumnView.Value.Name)%>
    </td>
    <td>
        <%=Html.HiddenFor(x => x.MatrixColumns[matrixColumnView.Key].DataTypeName) %>
        <%=Html.DisplayFor(x => x.MatrixColumns[matrixColumnView.Key].DataTypeName, (string)matrixColumnView.Value.DataTypeName) %>
    </td>
</tr>
<%} %>

Upvotes: 4

Views: 286

Answers (1)

Ant P
Ant P

Reputation: 25221

Instead of:

<%=Html.DisplayFor(x => x.MatrixColumns[matrixColumnView.Key].DataTypeName, (string)matrixColumnView.Value.DataTypeName) %>

Just try:

<%=Html.DisplayFor(x => x.MatrixColumns[matrixColumnView.Key].DataTypeName) %>

By passing in (string)matrixColumnView.Value.DataTypeName - which (presumably) evaluates to "Boolean" - as the second argument, you are telling MVC to look for a display template called "Boolean." Obviously, the template it finds can't display String values. Usually, you're better off letting the framework decide which display template to use.

There's a useful article here that talks about how MVC resolves display/editor templates:

http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html

Upvotes: 2

Related Questions