How to make a boolean HTML5 attribute 'conditional' in ASP.Net MVC? - c#

I'm using ASP.Net MVC (5.2.3.0) to create a form field:
#Html.TextBoxFor(
x => x.UserName,
new {
#class = "form-control",
placeholder = "Enter your username",
required = true,
autofocus = true
});
So far so good, but now I like to make the autofocus attribute conditional. How would I go about?
The autofocus attribute is a boolean attribute and W3C states:
Note: The values "true" and "false" are not allowed on boolean
attributes. To represent a false value, the attribute has to be
omitted altogether.
The following doesn't work in MVC, because it still renders the autofocus attribute causing the browser to do the auto focus:
autofocus = String.IsNullOrEmpty(this.Model.UserName)
autofocus = String.IsNullOrEmpty(this.Model.UserName) ? null : ""`
Does anybody know how to solve this problem?

You could create an attribute dictionary somewhere before in the view:
#{
var usernameAttrs = new Dictionary<string, object>
{
{"class ", "form-control"},
{"placeholder ", "Enter your username"},
{"required", true},
};
if (String.IsNullOrEmpty(this.Model.UserName))
{
usernameAttrs.Add("autofocus", true);
}
}
and use it in the TextBoxFor()
#Html.TextBoxFor(x => x.UserName, usernameAttrs);

check your condition in controller and if true set ViewBag.Tag = autofocus and then in your view
#Html.TextBoxFor(
x => x.UserName,
new {
#class = "form-control",
placeholder = "Enter your username",
required = true,
ViewBag.Tag
});

Related

MultiSelectList change dynamically ASP.NET MVC Razor

I'm using this code to generate a multi-select2. Tags is a MultiSelectList.
#Html.DropDownList("mail-to", (IEnumerable<SelectListItem>)ViewBag.Tags, String.Empty, htmlAttributes: new { multiple = "", #class = "form-control select2 select2-multiple" })
$("#mail-to").select2({
minimumResultsForSearch: -1,
closeOnSelect: false,
});
It works great. Now I want to change the select options with another ViewBag based on a checkbox field checked change event.
Is there a way to change select2 data populated with this type of list or a MVC way to do it?
What I've tryed:
$("#mail-to").select2({
tags: #ViewBag.TagsArea, //or tags: #Html.Raw((IEnumerable<SelectListItem>)ViewBag.TagsArea)
});
Managed to solve it:
var areas = #Html.Raw(Json.Encode(ViewBag.Tags)) ;
$("#mail-to").empty();
$.each(areas, function (index, element) {
$("#mail-to").append($('<option/>', {
value: element.Value, text: element.Text
}));
});

MultiLineText DataType Value not populating in TextAreaFor

I am attempting to implement an Update on a current text area value.
The datatype is set for multiline in my model
[DataType(DataType.MultilineText)]
public string Text { get; set; }
When the page loads for the textarea, it does not populate.
#Html.TextAreaFor(a => a.Text, new { #Value = Model.Text })
But for a textbox it does populate
#Html.TextBoxFor(a => a.Text, new { #Value = Model.Text })
Is there something I'm missing? this seems pretty straight forward.
#Html.TextAreaFor(a => a.Text, new { id = "SomeID", placeholder = "Text", Value = Model.Text})
#Html.TextAreaFor(m => m.UserName) should be enough - ASP MVC takes care of populate current value from model to textarea.
Using { #Value = Model.Text } doesn't apply to textarea as it does not uses value attribute: How to add default value for html <textarea>?

Set Html.TextBoxFor not editable depending on a Model value [duplicate]

This question already has answers here:
Enabling & disabling a textbox in razor view (ASP.Net MVC 3)
(4 answers)
Closed 5 years ago.
I'm developing an ASP.NET MVC 5 app with Razor, C# and .NET Framework 4.7.
I want to make it a textbox not editable if Model.IsChinaProduct is true.
I have this piece of code in a View:
#Html.TextBoxFor(m => m.Configurations[index].PkgRatio, new { #class = "productClass", #onkeydown = "IsValidKey(event);" #if (Model.IsChinaProduct) disabled})
I want to add the disabled attribute if Model.IsChinaProduct is true, but that code shows me the following error:
Error CS0746 Invalid anonymous type member declarator. Anonymous type
members must be declared with a member assignment, simple name or
member access.
How can I add the disabled attribute if Model.IsChinaProduct is true?
UPDATE:
Maybe disabled is not the right attribute.
AFAIK you can't, because there is no disabled="false", meaning you should do something like that:
#{
var htmlAttributes = Model.IsChinaProduct ? (object)
new { #class = "productClass", readonly = "readonly" }
: new { #class = "productClass", #onkeydown = "IsValidKey(event);" };
}
#Html.TextBoxFor(m => m.Configurations[index].PkgRatio, htmlAttributes)
For setting it ReadOnly, try this:
#{
object displayMode = (Model.IsChinaProduct) ? new { #class = "productClass", #onkeydown = "IsValidKey(event);" }
: new { #class = "productClass", #onkeydown = "IsValidKey(event);" readonly = "readonly"};
#Html.TextBoxFor(m => m.Configurations[index].PkgRatio, displayMode)
}
Dont use TextBoxFor if IsChinaProduct = true
Try DisplayFor combine with HiddenFor instead
like this
#if (Model.IsChinaProduct)
{
#Html.HiddenFor(m => m.Configurations[index].PkgRatio)
#Html.DisplayFor(m => m.Configurations[index].PkgRatio)
}
else
{
#Html.TextBoxFor(m => m.Configurations[index].PkgRatio)
}

Conditionally disabling a Bootstrap control

I am trying to enable or disable a control based on a value from a model. I was hoping I could use disabled="disabled" when I want the control to be disabled, or else, disabled = "" when I want it to work.
#Html.DropDownListFor(x => x.AccountTypeId, Model.AccountTypes, "Select One", new { #class = "form-control", #disabled = Model.ClosedDate.HasValue ? "disabled" : "" })
But this doesn't work, and the control is always disabled, regardless of the value. Is there a way I can do this, without using JavaScript or something?
Unfortunately the way the disabled attribute works in HTML is if present on an element, regardless of value, it marks the element as disabled.
So, you could modify your code to something like this:
#Html.DropDownListFor(x => x.AccountTypeId, Model.AccountTypes, "Select One", (Model.ClosedDate.HasValue ? new { #class = "form-control", #disabled = "disabled" } : new { #class = "form-control" })
Not the prettiest but should get the job done
One more point to remember is the fact that setting the input as disabled prevent the form to submit the value of the input, and you might get into some trouble when the mvc bind your model, because they will insert default values for the property disabled. If you want to post the value back to your controller, use readonly attribute instead of disabled.

RadioButton comes checked automatically

I used RadioButtonFor like this
#Html.RadioButtonFor(m => m.Content, Model.Content, new { #name = "rb", #class = "answer-radio", #id = "answer-" + Model.Counter,#checked = "false" })
#Html.Label(Model.Content, new { #for = "answer-" + Model.Counter })
#Html.HiddenFor(m => m.Content)
But this radiobutton comes "checked". How can i disable it ?
Are you sure you want a radio button? Seems like you might be after a Checkbox...
For a boolean, I would set up a 2 radiobuttons like so:
#Html.RadioButtonFor(m => m.Content, true, new { #id = "rb1" })
#Html.RadioButtonFor(m => m.Content, false, new { #id = "rb2" })
The html helper will figure out which one to check. If Model.Content is of another type, use different values for the radiobuttons and MVC will still figure out which one to check.
Edit:
Actually, it's even simpler than that. If the you use the Html helper RadioButtonFor method, it will check the radiobutton if it finds a value that matches the Model property. So you've specified your RadioButton as always having the same value as your Model property so it will always be checked (and that is the value that will be posted back in the form)
So, if you wanted a bool to default to false, and only return true if checked you could do just this:
#Html.RadioButtonFor(m => m.Content, true, new { #id = "rb1" })
where Content is originally set to false.
You can do it with other value types as well. e.g. if Content was a string, initially set to null, this would post back "RadioButtonChecked" only if the radio button was checked. Null otherwise:
#Html.RadioButtonFor(m => m.Content, "RadioButtonChecked", new { #id = "rb1" })
Adding "checked" to the attribute list will make it checked no matter what. I would make sure the value in your model is either null or false.

Categories

Resources