How to dynamically disable TextBox in MVC Razor? - asp.net-mvc

I want to dynamically disable/enable textbox aftre clicking the checkbox. How can I do it? I'm using this:
#{
object addInput = (Model.AddInput) ? null : new { disabled = "disabled" };
}
#Html.CheckBoxFor(model=> model.AddInput)
#Html.TextBoxFor(model => model.Input.Name, addInput)
but it works only on start. Clicking the checkbox isn't changing anything. How can do some binding to change disable state automaticaly?

This needs to be done in javascript.
#{
object addInput = (Model.AddInput) ? null : new { disabled = "disabled" };
}
#Html.CheckBoxFor(model=> model.AddInput)
#Html.TextBoxFor(model => model.Input.Name)
<script>
$('#AddInput').click(function() {
var $this = $(this);
if ($this.is(':checked')) {
$('#Name').removeAttr("disabled");
} else {
$('#Name').attr("disabled", "disabled")
}
});
</script>

Add jquery action on click on your checkbox and set state appropriately.

In case you want to enable it for some reason, you can also use the following:
$('#Name').attr("disabled", false);

Related

Razor EditorFor with Onclick Event

I have nullable Boolean value that is being presented as a checkbox using the following code:
#Html.EditorFor(m => m.IsInitialStatus, new { htmlAttributes = new { #onclick = "InitialOrStarting()" } })
however the #onclick attribute is not being added to the HTML when the page is loaded. Am I missing something here? I had taken the example from an answer on this page.
I have also looked at changing this to a CheckBoxFor but keep getting an issue with the nullable Bool datatypes.
Any help on this would be appreciated! I just want a nullable bool checkbox with an onClick event firing to a Javascript function... I am not the most advanced user but this seems to be more difficult for me to do than maybe it should!?
EDIT
There appears to be an EditorTemplate for Boolean which contains:
#model bool?
#Html.CheckBox("", Model.GetValueOrDefault())
You are using the overload of EditorFor() where the 2nd parameter is additionalViewData. If you did not have a specific EditorTemplate for bool?, the method would generate the default template, which is a <select> with 3 values for null, true and false, and include the attributes.
But because you have an EditorTemplate, you need to add the attributes yourself by reading the value from the ViewDataDictionary (typically, an EditorTemplate includes multiple html elements, so the method cannot know which element you want to apply the attributes to).
Your template would need to be
#model bool?
#{ var attributes = ViewData["htmlAttributes"]; }
#Html.CheckBox("", Model.GetValueOrDefault(), attributes)
Having said that, your should not be doing this. A bool? has 3 states (null, true or false) but a checkbox has only 2 states - on or off (translates to true or false) so your EditorTemplate does not represent the possible values of your property.
If you only want to allow true or false, then your property should not be nullable. Alternatively, use the default template that does allow a null selection (or if you want an alternative UI, create a template that renders 3 radio buttons for example)
In addition, I recommend you stop polluting you markup with behavior and use Unobtrusive JavaScript - i.e. your script will be
$(yourCheckBox).click(function() {
... // do something
});
Onclick Event does not working for #HtmlEditorFor. But you can use class attribute.
<script>
$(".single-checkbox").on("change", function () {
if ($(".single-checkbox:checked").length > 2) {
this.checked = false;
alert ("Only 2 choice")
}
});
</script>
#Html.EditorFor(model => model.YourProperty, new { htmlAttributes = new { #class = "single-checkbox" } })
#Html.EditorFor(model => model.YourProperty, new { htmlAttributes = new { #class = "single-checkbox" } })
#Html.EditorFor(model => model.YourProperty, new { htmlAttributes = new { #class = "single-checkbox" } })
#Html.EditorFor(model => model.YourProperty, new { htmlAttributes = new { #class = "single-checkbox" } })

check the checkbox which is reside in the textbox - asp.net mvc 4

I have created a checkbox using textbox in asp.net mvc 4 on view page like this.
#Html.TextBox("SomeID", "SomeValue" ,new { type = "Checkbox" })
now based on some condition, I would like to check this checkbox.
How could it be possible?
I have tried this,
#Html.TextBox("SomeID", "SomeValue" ,new { type = "Checkbox", value = "true" })
but it is not working.
Thank you.
First of all the way you are doing it does not make sense. If you want to use a checkbox then use #lagerone answer. If you need conditional check uncheck do something like following
#{
var someCondition = true;
}
#Html.CheckBox("test", someCondition)
The way you are rendering it, you can achieve it by following code.
#{
var someCondition = false;
}
#if (someCondition)
{
#Html.TextBox("SomeID", "SomeValue", new {type = "Checkbox", #checked = ""})
}else
{
#Html.TextBox("SomeID", "SomeValue", new { type = "Checkbox" })
}
Use your logic to assign some value to someCodition
TextBox != CheckBox
You could try
#Html.CheckBox("MyChecBox",true)

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>

How to update strongly typed Html.DropDownList using Jquery

I have a webpage with two radiobuttons and a dropdownlist as follows:
<div class="sectionheader">Course
<div class="dropdown"><%=Html.DropDownList("CourseSelection", Model.CourseList, new { #class = "dropdown" })%> </div>
<div class="radiobuttons"><label><%=Html.RadioButton("CourseType", "Advanced", false )%> Advanced </label></div>
<div class="radiobuttons"><label><%=Html.RadioButton("CourseType", "Beginner", true )%> Beginner </label></div>
</div>
The dropdownlist is strongly typed and populated with Model.CourseList (NB - on the first page load, 'Beginner' is the default selection and the dropdown shows the beginner course options accordingly)
What I want to be able to do is to update the DropDownList based on which radiobutton is selected i.e. if 'Advanced' selected then show one list of course options in dropdown, and if 'Beginner' selected then show another list of courses.
Edit - posted my own answer below to show solution that worked for me (finally!)
Continue to return your collection of selectlistitem; this translates to JSOn nicely, at least it should, as an array of objects that look like { text: "a", value: "1" } and you can loop through the array and recreate the list this way...
So it will work with strongly-typed objects. You just have to take the objects and construct the elements for the underlying drop down.
HTH.
The code I would like to call sits within my Controller:
public ActionResult UpdateDropDown(string courseType)
{
IDropDownList dropdownlistRepository = new DropDownListRepository();
IEnumerable<SelectListItem> courseList = dropdownlistRepository.GetCourseList(courseType);
return Json(courseList);
}
Using examples provided in jQuery in Action, I now have the following jQuery code:
$('.radiobuttons input:radio').click(function()
{
var courseType = $(this).val(); //Get selected courseType from radiobutton
var dropdownList = $("#CourseSelection"); //Ref for dropdownlist
$.post("/ByCourse/UpdateDropDown", { courseType: courseType }, function(data) {
$(dropdownList).loadSelect(data);
});
});
The loadSelect function is taken straight from the book and is as follows:
(function($) {
$.fn.emptySelect = function() {
return this.each(function() {
if (this.tagName == 'SELECT') this.options.length = 0;
});
}
$.fn.loadSelect = function(optionsDataArray) {
return this.emptySelect().each(function() {
if (this.tagName == 'SELECT') {
var selectElement = this;
$.each(optionsDataArray, function(index, optionData) {
var option = new Option(optionData.Text, optionData.Value);
if ($.browser.msie) {
selectElement.add(option);
}
else {
selectElement.add(option, null);
}
});
}
});
}
})(jQuery);

DropDown list onchange event and AJAX in MVC

I have a code block in my MVC view as follows:
<%using (Ajax.BeginForm("MyAction", new { action = "MyAction", controller = "Home", id = ViewData["selected"].ToString() }, new AjaxOptions { UpdateTargetId = "Div1" }))
{ %>
<%=Html.DropDownList("ddl", ViewData["MyList"] as SelectList, new { onchange = "this.form.submit()" })%>
<%} %>
I want to set the value of ViewData["selected"] so that i can send it to the desired action.
Can anyone please suggest how can i do this?
thanks!
Instead of using a form, why not use a jQuery onChange event on your drop down?
$(document).ready(function() {
$("#ddl").change(function() {
var strSelected = "";
$("#ddl option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Home/MyAction/" + strSelected;
$.post(url, function(data) {
// do something if necessary
});
});
});
ViewData is not the place to pass data back to the server side. Values of html input controls within form tag are conveniently available in action method. You can get these values either from various types of action method arguments (model, formcollection etc).
Here is a link to free asp.net mvc ebook tutorial. Is a good resource for asp.net mvc.
Found solution at this post it is just small chnge
Yes, that’s right – only change is replacing:
onchange = “this.form.submit();”
with:
onchange = “$(this.form).submit();”

Resources