0

I have tried to insert a string variable inside a textboxfor to complete his parameters, but the result is something as variablename=.....

For example, if I want disable the textbox depending on boolean in the modelview :

@string isDisabled = (Model.kbinding_boolvar ? "disabled" : ""); 
@Html.TextBoxFor(m => m.kbinding_namevar, new { @class = "classname", @is_disabled })

The html output is this :

<input class="classname" isDisabled="disabled" data-val="true" name="kbinding_textbox_name" type="text" value="" />

instead of :

<input class="classname" disabled data-val="true" name="kbinding_textbox_name" type="text" value="" /> 

What's the correct syntax to use to achieve the result?

1
  • you have missed the values try @Html.TextBoxFor(m => m.kbinding_namevar, new { @class = "classname", disabled = is_disabled}) what happens is, asp.net mvc is taking the attribute and value i.e both as is_disabled. You have to explicitly say the attribute name. Alternativey you can name your variable as disabled and then you don't need an explicit attribute name Commented Nov 24, 2015 at 11:52

2 Answers 2

5

Define the attributes as an object

@{
    var attributes = Model.kbinding_boolvar ? 
    (object)new { @class = "classname", disabled = "disabled" } :
    (object)new { @class = "classname"};
}

@Html.TextBoxFor(m => m.kbinding_namevar, attributes)
Sign up to request clarification or add additional context in comments.

Comments

0

Basically you have missed the attribute name i.e disabled because your variable name is different then attribute. That's why you see this;

 <input class="classname" isDisabled="disabled"  data-val="true"   name="kbinding_textbox_name" type="text" value="" />

If you rename your variable same like an attribute i.e isDisabled to disabled like below then it will give you correctly result;

@{ string disabled= (Model.kbinding_boolvar ? "disabled" : ""); }
@Html.TextBoxFor(m => m.kbinding_namevar, new { @class = "classname", disabled})

Or be explicit

@{ string isDisabled = (Model.kbinding_boolvar ? "disabled" : ""); }
@Html.TextBoxFor(m => m.kbinding_namevar, new { @class = "classname", disabled = is_disabled})

Note: You don't need @ i.e @is_disabled as you are already in code expression

2 Comments

Thank you, i have already tried this solution but does not work because when in html ther's the key "disabled" the component is always disabled with any value (ex disabled="No")
agree but your generated html code it isn't the key but the value i.e isDisabled="disabled" which is not a valid attribute (isDisabled) if its like this disabled="disabled" then it will work or just like this disabled

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.