I've got a textbox element which is being rendered inside of my .ascx file using MVC's mark-up:
<%= Html.TextBoxFor(model => model.AssignedOperatorDisplayName, new
{
@class = "assignedOperatorDisplayNameTextArea"
})
%>
I now need to conditionally disable this textbox element. Initially, I attempted to do so by setting the disabled attribute to true or false:
<%= Html.TextBoxFor(model => model.AssignedOperatorDisplayName, new
{
@class = "assignedOperatorDisplayNameTextArea",
disabled = Model.IsElementDisabled()
})
%>
Unfortunately, this does not work because the browser interprets the presence of the disabled attribute as "true" regardless of whether its value is set to true or false as seen here: http://jsfiddle.net/zWQbL/
So, I'm left wondering how to do this. I was playing around with merging two anonymous objects together using the following article: Merging anonymous types but this isn't working and it feels really wrong.
Any ideas?
EDIT: I'm went with this answer, but there are a few ways to achieve the result. I'd encourage anyone looking at this to consider there needs before using one solution over another.
<%= Html.TextBoxFor(model => model.AssignedOperatorDisplayName, new Dictionary<string, object>()
{
{
"class", "assignedOperatorDisplayNameTextArea"
}
}.WithAttrIf(Model.IsTaskComplete(), "disabled", "true"))%>
public static Dictionary<string, object> WithAttrIf(this Dictionary<string, object> dictionary, bool condition, string attrname, object value)
{
if (condition)
dictionary[attrname] = value;
return dictionary;
}