MVC 5 TextBoxFor not able to do conditional Bootstrap CSS? - asp.net-mvc

I'm using a TextBoxFor and what I need to do is see if a property is NULL or Blank. If so then I need to let the end user type in their info. If not, meaning I can find their name, I need to disable the field so that they can not alter it.
I did some searching and try these two options but they are not working.
#Html.TextBoxFor(m => m.EmployeeName, string.IsNullOrWhiteSpace(Model.EmployeeName) ? new { Class = "form-control" } : new { Class = "form-control", disabled = "disabled" })
#Html.TextBoxFor(m => m.EmployeeName, new { Class = "form-control", string.IsNullOrWhiteSpace(Model.EmployeeName) ? disabled = "disabled" : null })
Any ideas on what I can try?

Your current code would be giving an error because there is no implicit conversion between the 2 anonymous types and you would need to cast them to object
var attributes = String.IsNullOrWhiteSpace(Model.EmployeeName) ?
(object)new { #class = "form-control" } :
(object)new { #class = "form-control", disabled = "disabled" })
#Html.TextBoxFor(m => m.EmployeeName, attributes)
Note however that disabling an control means its value will not be submitted, so if EmployeeName initially has a value, it will be null when submitted. You might want to consider using readonly = "readonly" instead.

Related

How do I set dynamic readonly on MVC 5 razor view?

I have a bool value IsAcre. If true, then textbox needs to be able to accept a value. If false, the textbox should be readonly. I am trying a couple different ways:
#Html.EditorFor(model => model.Activity.Acres, new { htmlAttributes = new { #class = "form-control", Model.Activity.IsAcres ? null : #readonly = "readonly" }} )
and
#Html.TextBoxFor(model => model.Activity.Volume, new { #class = "form-control", #readonly = "#Model.Activity.IsVolume" })
First one seems to be syntacticlly incorrect, the second one renders as:
readonly="False"
Even though it renders the false readonly, the textbox is still set to readonly, I assume because the bool value is passed as a string.
Is there a way to do this inline or will have to if/else on the entire textbox?
The readonly attribute is a boolean attribute which means that its presence represents the true value, so your second code snippet that renders readonly="False" makes the input readonly (although its invalid html). Note also from the specs
The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.
You need to use the code in your first code snippet to ensure the attribute is either added or omitted, although you could use alternatives such as
#{ var attributes = Model.Activity.IsAcres ? (object)new { #class = "form-control"} : (object)new { #class = "form-control", readonly = "readonly" }; }
#Html.TextBoxFor(model => model.Activity.Volume, attributes)
and if this is something you use regularly, then you could create a HtmlHelper extension method that conditionally adds the attribute based on the value of another property (say)
#Html.ReadOnlyTextBoxIf(m => m.Activity.Acres, Model.Activity.IsAcres, new { #class = "form-control" })

Conditionally disable textbox in Razor view

Its a quick question.
#Html.TextBoxFor(model => model.VIN, string.IsNullOrEmpty(Model.VIN) ? new { #class = "required Vin" } : new { #disabled = "disabled" })
I get the error that Type of expression can not be determined because there is no implicit conversion anonymous type #1 and anonymous type #2.
Is there a way to conditionally disable text box?
Try something like
#Html.TextBoxFor(model => model.VIN, string.IsNullOrEmpty(Model.VIN) ? new { #class = "required Vin" } : (object)new { disabled = "disabled" })

Html.Dropdownlist selected value not working

In my project, Html.DropdownList could not display its selected value.It displays the initial value of the list.My controller and view codes are given below:
Controller:
public ActionResult Edit(int id = 0)
{
PERMISSION permission = permissionManager.Find(id);
ViewBag.MODULE_ID = new SelectList(moduleManager.GetAll(), "ID", "TITLE",permission.MODULE_ID);
return View(permission);
}
View :
#Html.DropDownList("MODULE_ID", (IEnumerable<SelectListItem>)#ViewBag.MODULE_ID, new { #class = "form-control" })
But if I write :
#Html.DropDownList("MODULE_ID", String.Empty)
It works fine.but I have to add the class="form-control".What should be solution?
UPDATE:
I have changed the ViewBag name from ViewBag.MODULE_ID to ViewBag.ModuleList. It may conflicts with the name of the dropdownlist. and now It works fine.
I have changed the ViewBag name from ViewBag.MODULE_ID to ViewBag.ModuleList. It may conflicts with the name of the dropdownlist. and now It works fine.
You are adding the form-control class in the wrong parameter. currently it is being added as the option label.
Use this:
#Html.DropDownList("MODULE_ID", (IEnumerable<SelectListItem>)#ViewBag.MODULE_ID, "-- Select --", new { #class = "form-control" })
On a side note, you should consider using a ViewModel class and doing away with both the magic string "MODULE_ID" and the ViewBag magic property. A ViewModel class allows you to strongly name things without casting, like this:
#Html.DropDownListFor(model => model.MODULE_ID, Model.Modules, "-- Select --", new { #class = "form-control" })
It's a subtle looking change but everything is compile time checked.
what works for me according to previous solution:
in controller:
ViewBag.VCenter = new SelectList(db.VirtualMachinesData.Where(x => x.IsVCenter == true).ToList(), "Id", "IPAddress","80"); ;
in View:
#Html.DropDownList("v", (IEnumerable<SelectListItem>)#ViewBag.VCenter, new { #class = "form-control" })
Important note: the name of dropdownlist -"v"- must be different from the name of viewbag -"VCenter"-, if same names it didn't work.

Enabling & disabling a textbox in razor view (ASP.Net MVC 3)

I want to Enable or Disable a textbox based on the value (Model.CompanyNameEnabled).
The below code is not working. Please rectify.
#{
string displayMode = (Model.CompanyNameEnabled) ? "" : "disabled = disabled";
#Html.TextBox("CompanyName", "", new { displayMode })
}
#{
object displayMode = (Model.CompanyNameEnabled) ? null : new {disabled = "disabled" };
#Html.TextBox("CompanyName", "", displayMode)
}
You should pass htmlAttribute as anonymous object, with property names = html attribute names, property values = attribute values. Your mistake was that you were passing string instead of name=value pair
<input id="textbox1" type="text" #{#((Model.CompanyNameEnabled) ? null : new { disabled = "disabled" })}; />
Haven't tested it, but should work
A simple approach:
#Html.TextBoxFor(x => x.Phone, new { disabled = "disabled", #class = "form-control" })
As is already mentioned in this thread the suggested answer doesn't work in MVC5 anymore. There's actually an easy two step solution to that problem.
Assign a class to the HTML inputs you want to be disabled / enabled (id will do for a single item just as fine of course). In the example below I assigned a class 'switch-disabled' to the input.
#Html.TextBox("CompanyName", "", new { htmlAttributes = new { #class = "form-control switch-disable" } })
Use javascript(jquery) to enable / disable the disabled parameter in HTML. In my example below I do this at the page load.
<script>
$(document).ready(() => {
if(#Model.CompanyNameEnabled)
{
$('.switch-disable').attr("disabled", false);
}else{
$('.switch-disable').attr("disabled", true);
}
});
</script>

Html.TextBox conditional attribute with ASP.NET MVC Preview 5

I have a strongly-typed MVC View Control which is responsible for the UI where users can create and edit Client items. I'd like them to be able to define the ClientId on creation, but not edit, and this to be reflected in the UI.
To this end, I have the following line:
<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, new
{ #readonly =
(ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0
? "readonly" : "false")
} )
%>
It seems that no matter what value I give the readonly attribute (even "false" and ""), Firefox and IE7 make the input read-only, which is annoyingly counter-intuitive. Is there a nice, ternary-operator-based way to drop the attribute completely if it is not required?
Tough problem... However, if you want to define only the readonly attribute, you can do it like this:
<%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId,
ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0
? new { #readonly = "readonly" }
: null)
%>
If you want to define more attributes then you must define two anonymous types and have multiple copies of the attributes. For example, something like this (which I don't like anyway):
ClientId.Length > 0
? (object)new { #readonly = "readonly", #class = "myCSS" }
: (object)new { #class = "myCSS" }
If you want to define several attributes, and conditional readonly without duplicate the other attributes,
you can use Dictionary instead of anonymous types for the attributes.
e.g.
Dictionary<string, object> htmlAttributes = new Dictionary<string, object>();
htmlAttributes.Add("class", "myCSS");
htmlAttributes.Add("data-attr1", "val1");
htmlAttributes.Add("data-attr2", "val2");
if (Model.LoggedInData.IsAdmin == false)
{
htmlAttributes.Add("readonly", "readonly");
}
#:User: #Html.TextBoxFor(
m => m.User,
htmlAttributes)
Tip: Its the mere presence of readonly/disabled attribute that makes the element readonly or disabled in the browser.
#Html.TextBoxFor(x => x.Name, isReadonly ?(object) new { #readonly = true } : new { /*Some other attributes*/ })
And alternative is just to emit it as plain old HTML. Yes, the editor will make you think you are wrong, but that seems to happen quite frequently with VS2008SP1. This example is specifically for checkboxes which seems to be completely wasted in CTP5, but it gives you an idea how to emit conditional attributes.
<input type="checkbox" name="roles" value='<%# Eval("Name") %>'
<%# ((bool) Eval("InRole")) ? "checked" : "" %>
<%# ViewData.Model.IsInRole("Admin") ? "" : "disabled" %> />
I think it should be
<%= ((bool) Eval("InRole")) ? "checked" : "" %>
instead of this in leppies answer.
<%# ((bool) Eval("InRole")) ? "checked" : "" %>
At least it did not work for me with # but it worked with =. Did i do anything wrong? Thanks for the tip anyway :)
i use this :
#Html.TextAreaFor(model => model.ComentarioGestor, comentarioGestor? new { #class = "form-control" } : new { #class = "form-control", #readonly = "readonly" } as object)
$(function() {
$("[readonly='false']").removeAttr("readonly");
});
I tried most of the suggestions above and now I have arrived at the simplest with a single line. Combine 2 anonymous html attributes object by declaring wither one of it as "object" type.
#Html.TextBoxFor(m => m.Email, !isEdit ? new { id = "email_box" } : new { id = "email_box", #readonly = isEdit ? "readonly" : "false" } as object)

Resources