2

I am new to MVC and working on an MVC4 Application.

What I wan to do is I want to disable my Dropdown if it is empty.

View->

@Html.DropDownList("UserName", null, string.Empty)

Controller->

ViewBag.UserName = new SelectList(lstUserName, "username", "username");

UserName is my viewbag which contains the list of items to fill dropdown.

Now if lstUserName is empty,I want to disable the DropDown..How can I achieve that..

1 Answer 1

1
@if (@ViewBag.UserName.Items.Count == 0)
{
@Html.DropDownList("UserName", null, string.Empty, new { @disabled=true})
}
else
{
 @Html.DropDownList("UserName", null, string.Empty)
}

You could use @readonly aswell, instead of @disabled.

Sign up to request clarification or add additional context in comments.

9 Comments

Your first version wouldn't work. As far as I know, disabled is based on the presence of the attribute, not the value contained within.
@Farzi Try for List of one item.
@SimonBelanger I tested this out on my own machine and it works for me. I am using MVC4 tho, maybe it doesn't work in older versions.
@Thousand It will work for list with 0 items. Disabled="false" is still disabling a field. Check the W3C specification or better yet, if you have chrome, right click the comment box click inspect element and add an attribute with disabled='false'. It will be disabled. If your browser is enabling the box, it's not a standard behavior and should be avoided. Nothing to do with MVC, this is an HTML specification.
@SimonBelanger ah indeed, i just tested it and it doesn't work. The second option still does though.
|

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.