views:

90

answers:

3

Hi all,

I've inherited the following code and i was wondering if i could pick at your brains to see if there's a nicer way to do duplicate this.

Heres the html for most of our partial input views

<% if (Html.IsInputReadOnly()) { %>
<td>
    Id
</td>
<td>
<%= Html.TextBox(
   "Id"
   , (Model == null ? null : Model.Id)
   , new { @readonly = "readonly", @disabled="disabled" }
 )%>
 <% } elseif (Html.IsInputDisplayable() == false) { %>
 <td></td>
 <td></td>
 <% } else { %>
 <td>Id</td>
 <td><%= Html.TextBox("Id")%>
  <%= Html.ValidationMessage("Id", "*")%>
 </td>
<%} %>

Here are my entension methods

public static bool IsInputReadOnly(this HtmlHelper helper)
{
    string actionName = ActionName(helper);

    // The Textbox should be read only on all pages except for the lookup page
    if (actionName.ToUpper().CompareTo("EDIT") == 0)
        return true;
    return false;
}

public static bool IsInputDisplayable(this HtmlHelper helper)
{
    string actionName = ActionName(helper);

    // The Textbox should be read only on all pages except for the lookup page
    if (actionName.ToUpper().CompareTo("CREATE") == 0)
        return true;
    return false;
}

Thanks in advance

A: 

I would separate out the read-only and editable portions into 2 separate partial views. Leave it to your controller to decide which view should be rendered. You should not be making these kind of decisions in your views - they should be dumb.

Keith Rousseau
I agree that views need to be dumb, but what in case of "control x should be enabled for condition 1, but disabled for condition 2" scenario's? So, I give a +1 to the question.
Sunny
A: 

If you could create a cutom ViewModel class which has a collection of KeyValue pair where key = control name & Value = HtmlAttributes for that control, the controller might be able to set these attributes.

On the View, you will directly bind the HtmlAttribute to the control.

Have not tried it out, but might work...

HTH

EDIT: the KeyValue pair HtmlAttributes might be a collection of flags like IsEditable, IsVisible etc. which can be interpreted on the View via an extension method to render HtmlAttributes as needed so that we are not mixing the HTML part into the controller

Sunny
+1  A: 

Can you wrap all that logic into a single extension method?

<%= Html.SmartDisplay("Id", (Model == null ? null : Model.Id))%> 

Then in the extension method, put all the code that checks whether it's displayable or readonly. This won't work if you don't have standard table layouts on all pages and for all controls, but if you do, it might work.

Mac