Applying Kendo button K-state-disabled class removing functionality of button - button
if(data[keyvar]==false)
{
jQuery('#BtnsaveAjax').prop("disabled", false).removeClass("k-state-disabled");
}
After I execute this statement the function which is present on the save button is not getting called. Do I need to add or remove any more classes to get that function back?
I want to try to answer your question but first what i grasp from your question is
i have a grid.. and to edit it i have a popup window.. on which there
are two buttons.. edit and save.. i have two view modes.. edit and
view.. in edit mode the save button is disabled and in view mode save
button is disabled..
so now when i click "the button" here i think refers to edit button then i want my save button to enable. So far this is what i've got,
first when you click view details you will see save button disabled
while edit button enabled,
then when you click edit button the save button will be enabled
DEMO
This is what my popup looks like.. so now when i click my edit button i want the save button to get enabled.. so buy adding that k-State-disabled i could manage that.. but now when i click my save button.. the click function i have added on save is not firing..
this is my code for that popup page .. and the Editable is a dictionary which contains the disabled value for ta particular kendo widget.
#using Kendo.Mvc.UI;
#using Newtonsoft.Json;
#using SampleUIApp.Areas.AreaOne.Models;
#using SampleUIApp.Common;
#model SampleUIApp.Areas.AreaOne.Models.MemberModel
<script type="text/javascript">
$(document).ready(function ()
{
// For setting control mode
// It is observed that Kendo Multiselect does not accept value through below code
// change mode of multiselect like done below in the same view
var Edit = #(Html.Raw(JsonConvert.SerializeObject((Dictionary<string, bool>)ViewBag.Editable)));
for ( keyVar in Edit )
{
if (keyVar.search("Btn") != -1) {
jQuery('#' + keyVar).attr("disabled", Edit[keyVar]);
} else {
jQuery('#' + keyVar).prop("readonly", Edit[keyVar]);
}
}
var viewMode = #Html.Raw(Json.Encode(ViewBag.ViewMode));
if(viewMode == 'ADD')
{
$("#LoanGrid1").remove();
}
var title = viewMode + ' MEMBER';
setTitle(title);
});
function setViewMode(data) {
//for ( keyVar in data ) {
// if (keyVar.search("Btn") != -1) {
// jQuery('#' + keyVar).attr("disabled", data[keyVar]);
// }
// else {
// jQuery('#' + keyVar).prop("readonly", data[keyVar]);
// }
for ( keyVar in data ) {
if (keyVar.search("Btn") != -1) {
if(data[keyVar]==true){
jQuery('#' + keyVar).prop("disabled", true).addClass("k-state-disabled");
}
else{
jQuery('#' + keyVar).prop("disabled", false).removeClass("k-state-disabled");
}
}
else {
jQuery('#' + keyVar).prop("readonly", data[keyVar]);
}
}
}
function onAdditionalData() {
return {
text: $("#CityName").val()
};
}
function AccessModelDetails() {
var data = #Html.Raw(Json.Encode(this.Model));
alert(data.Remark);
}
function UpdateModelDetails() {
// var model = $('form').serialize();
// var data = Sys.Serialization.JavaScriptSerializer.deserialize(model);
// alert('model: ' + data.Remark);
$("#Remark").val("Remark Updated");
}
function saveDetails() {
alert('Calling : saveDetails');
var model = $("form").serialize();
Save(model); // Save Function is Written On Parent View
}
function Edit() {
var mode = 2; // 2 For Edit
var Fid = 0;
var viewName = 'MemberEditor';
var actionURL = '#Url.Action("setViewMode", "Member")';
$.ajax({
type: "POST",
data: {
Mode: mode,
lFeatureId: Fid,
ViewName: viewName
},
url: actionURL,
success: function (result) {
setViewMode(result);
}
});
}
// This Function will be called when an item is got selected from Multiselect Control
// Used for Member role
// here is a sample methos to get the selected item.
function OnSelectMemberRole(e) {
var dataItem = this.dataSource.view()[e.item.index()];
alert("event :: select (" + dataItem.MemberRoleName + " : " + dataItem.MemberRoleId + ")");
}
</script>
#using (Html.BeginForm())
{
<div class="editor">
<div id="DIV_Line07" class="line">
<div id="DIV_Buttons" class="col100" style="float: right">
#*
1.Below is the kendo button to call server side controller action by using MultiButton Attribute
2. Have to Set HtmlAttributes as follows
* name = Given Name With MutiButton Attribute
* type = "submit",
* value = Given Name With MutiButton Attribute
3. .Name(Given Name With MutiButton Attribute)
4. .Content("Caption Of Button")
*#
#(Html.Kendo().Button()
.Name("BtnEditAjax")
.Content("Edit - AJAX")
.HtmlAttributes(new { style = "float:right", type = "button" })
.Events(ev => ev.Click("Edit"))
)
#* #(Html.Kendo().Button()
.Name("Btnsave")
.HtmlAttributes(new { style = "float:right", name = "Btnsave", type = "submit", value = "save" })
.Content("Save - Server")
)*#
#*
1.Below is the kendo button to call server side controller action by using Javascript Function With Ajax
2. Have to Set HtmlAttributes as follows
* type = "button",
3. .Name(Name Of The Button)
4. .Content("Caption Of Button")
5. Events(ev => ev.Click("Javascript Function Name"))
*#
#(Html.Kendo().Button()
.Name("BtnsaveAjax")
.Content("Save - AJAX")
.HtmlAttributes(new { style = "float:right", type = "button" })
)
#(Html.Kendo().Button()
.Name("AccessModelinJS")
.Content("Access Model In JS")
.HtmlAttributes(new { style = "float:right", type = "button" })
.Events(ev => ev.Click("AccessModelDetails"))
)
#(Html.Kendo().Button()
.Name("UpdateModelinJS")
.Content("Update Model In JS")
.HtmlAttributes(new { style = "float:right", type = "button" })
.Events(ev => ev.Click("UpdateModelDetails"))
)
</div>
</div>
<div id="DIV_Line00" class="line">
<div id="DIV_Fname" class="col33">
#Html.HiddenFor(model => model.MemberId)
<label>
First Name - Upper Case
</label>
#*To make textbox uppercase set style's "text-transform" Attribute's value as "uppercase" in html HtmlAttributes*#
#(Html.Kendo().TextBoxFor(m => m.FirstName)
.Name("FirstName")
.HtmlAttributes(new { #class = "width100", style = " text-transform: uppercase" })
)
</div>
<div id="DIV_MName" class="col33">
<label>
Middle Name - Lower Case
</label>
#*To make textbox lowercase set style's "text-transform" Attribute's value as "lowercase" in html HtmlAttributes*#
#Html.Kendo().TextBoxFor(m => m.MiddleName).Name("MiddleName").HtmlAttributes(new { #class = "width100", style = " text-transform: lowercase" })
</div>
<div id="DIV_LName" class="col33">
<label>
Last Name - Alphabets Only
</label>
#*To make textbox AlphaOnly set pattern Attribute's value as "[A-Za-z\\s]*" in html HtmlAttributes*#
#Html.TextBoxFor(m => m.LastName, new { id = "LastName", #class = "width100 k-textbox", type = "text", pattern = "[A-Za-z\\s]*" })
</div>
</div>
<div id="DIV_Line01" class="line">
<div id="DIV_Height" class="col15">
<label>
DOB - Min & Max
</label>
#Html.ValidationMessageFor(model => model.DateOfBirth)
#(Html.Kendo().DatePickerFor(m => m.DateOfBirth)
.Min(new DateTime(1970, 01, 01))
.Max(new DateTime(2014, 11, 30))
.HtmlAttributes(new { #class = "width100" })
.Format("dd/MM/yyyy")
)
</div>
<div id="DIV_Membe rName" class="col18">
<label>
Age - Integer
</label>
#Html.ValidationMessageFor(model => model.Age)
#Html.Kendo().IntegerTextBoxFor(m => m.Age).HtmlAttributes(new { #class = "width100" })
</div>
<div id="DIV_Age" class="col15">
<label>
Height-Decimal 3
</label>
#*Format as "#.000" specifies that 3 decimals will be displayed, Number of 0s in the format Specifies number of decimals*#
#Html.ValidationMessageFor(model => model.Height)
#Html.Kendo().NumericTextBoxFor(m => m.Height).HtmlAttributes(new { #class = "width100" }).Format("#.000")
</div>
<div id="DIV_Country" class="col18">
<label>
StateAutoComplete
</label>
#* 1.Name Of the autocomplete must be ur property name of the model so that it could bind selected value to model .
2.List for autocomplete will only contains value and does not support Id Value pair pattern(In Used Version of kendo).
*#
#(Html.Kendo().AutoCompleteFor(m => m.StateName)
.Name("StateName")
.DataTextField("StateName")
.BindTo((System.Collections.IEnumerable)ViewData["states"]).HtmlAttributes(new { #class = "width100" })
)
</div>
<div id="DIV_CityServer" class="col33">
<label>
City-AutoComplete Server Filtering
</label>
#* 1.Name Of the autocomplete must be ur property name of the model so that it could bind selected value to model .
2.List for autocomplete will only contains value and does not support Id Value pair pattern(In Used Version of kendo).
*#
#(Html.Kendo().AutoCompleteFor(m => m.CityName)
.Name("CityName")
.DataTextField("CityName")
.MinLength(3)
//.BindTo((System.Collections.IEnumerable)ViewData["cities"]).HtmlAttributes(new { #class = "width100" })
.DataSource(
source =>
{
source.Read(read => { read.Action("GetCities", "Member").Data("onAdditionalData"); });
source.ServerFiltering(true);
})
.HtmlAttributes(new { #class = "width100" })
)
</div>
</div>
<div id="DIV_Line02" class="line">
<div id="DIV_DateOfBirth" class="col33">
<label>
Member Type - DropDownList
</label>
#*
0.List can be bind to DropDownListFor using "BindTo" or using "DataSource".
1.Name Of the DropDownListFor must be ur property name of the model so that it could bind selected value to model .
2.List for DropDownListFor will contains Id Value pair .
3.Selected Value will be Value of DataValueField - ".DataValueField("MemberTypeId")"
4.Selected Value will bind to model property given as name to DropDownListFor
*#
#(Html.Kendo().DropDownListFor(m => m.MemberType)
.Name("MemberType")
.DataTextField("MemberTypeName")
.DataValueField("MemberTypeId")
.HtmlAttributes(new { #class = "width100" })
.Filter("contains")
.BindTo((System.Collections.IEnumerable)ViewData["memberTypes"])
//.DataSource(
// source =>
// {
// source.Read(read => { read.Action("GetMemberTypes", "Member"); });
// })
)
</div>
<div id="DIV_MemberRole" class="col33">
<label>
Member Role - MultiSelect
</label>
#*
0.List can be bind to MultiSelectFor using "BindTo" or using "DataSource".
2.List for MultiSelectFor will contains Id Value pair .
1.Name Of the MultiSelectFor must be ur property name of the model so that it could bind selected values to model.
2.Type of property Specified in Name of MultiSelectFor has to be a collection type for example List<long> or List<string>.
3.Selected Values will be Values of DataValueField - ".DataValueField("MemberRoleId")"
4.Selected Values will bind to model property given as name to MultiSelectFor
*#
#(Html.Kendo().MultiSelectFor(m => m)
.Name("MemberRoleList")
.DataTextField("MemberRoleName")
.DataValueField("MemberRoleId")
.BindTo((System.Collections.IEnumerable)ViewData["memberRoles"])
.Events(e => e.Select("OnSelectMemberRole"))
//.DataSource(
// source =>
// {
// source.Read(read => { read.Action("GetMemberRoles", "Member"); });
// })
)
</div>
<div id="DIV_Mobile" class="col33">
<label>
Mobile - Mobile Mask
</label>
#*
1. Specifying Mask As "0000000000" allows to enter only 10 Digits.
*#
#Html.ValidationMessageFor(model => model.Mobile)
#(Html.Kendo().MaskedTextBoxFor(m => m.Mobile)
.Mask("0000000000")
.HtmlAttributes(new { #class = "width100" })
)
</div>
</div>
<div id="DIV_Line03" class="line">
<div id="DIV_Email" class="col33">
<label>
Email - With Validation
</label>
#*
1. For Email Validation On UI, Use Html.TextBoxFor
2. Set Attributes as follows
* type = "email"
* #class = "k-textbox"
* style = " text-transform: lowercase"
*#
#Html.TextBoxFor(model => model.Email, new { #class = "k-textbox width100", type = "email", style = " text-transform: lowercase" })
</div>
<div id="DIV_PIN" class="col33">
<label>
PIN - Mask
</label>
#*
1. Specifying Mask As "000000" allows to enter only 6 Digits.
*#
#(Html.Kendo().MaskedTextBoxFor(m => m.PIN)
.Mask("000000")
.HtmlAttributes(new { #class = "width100" })
)
</div>
<div id="DIV_Phone" class="col33">
<label>
Phone - Mask
</label>
#*
1. Specifying Mask As "(999) 000-0000" allows to enter Digits within specified mask.
*#
#(Html.Kendo().MaskedTextBoxFor(m => m.Phone)
.Mask("(999) 000-0000")
.HtmlAttributes(new { #class = "width100" })
)
</div>
<div id="DIV_Line05" class="line">
</div>
<div id="DIV_Line06" class="line">
<div id="DIV_Remark" class="col100">
<label>
Remark - Text Area
</label>
#*
To Use Text Area us helper Html.TextAreaFor
2. Set Attributes as follows
* #class = "k-textbox"
* style = " text-transform: lowercase"
* rows = as much U Want
* cols = as much U Want
*#
#Html.TextAreaFor(m => m.Remark, new { #class = "k-textbox width100", rows = "2", cols = "50" })
#Html.HiddenFor(m => m.Remark, new { id = "Remark" })
#* <textarea class="k-textbox" rows="2" cols="50" >
</textarea>*#
</div>
</div>
<div id="DIV_Phone" class="col100">
<label>
Loan Details
</label>
#(Html.Kendo().Grid<LoanModel>()
.Name("LoanGrid1")
.Columns(columns =>
{
columns.Bound(m => m.LoanNumber).Filterable(false).Title("Loan Number").Width("20%").HtmlAttributes(new { #style = "font-size:x-small" });
columns.Bound(m => m.ROI).Filterable(false).Title("ROI").Width("10%").Format("{0:N2}").HtmlAttributes(new { #style = "font-size:x-small" });
columns.Bound(m => m.Period).Filterable(false).Title("Period").Width("10%").Format("{0:N2}").HtmlAttributes(new { #style = "font-size:x-small" });
columns.Bound(m => m.LoanAmount).Filterable(false).Title("Loan Amount").Width("10%").Format("{0:N2}").HtmlAttributes(new { #style = "font-size:x-small" });
columns.Bound(m => m.OtstngAmount).Filterable(false).Title("Outstanding amount").Width("10%").Format("{0:N2}").HtmlAttributes(new { #style = "font-size:x-small" });
columns.Command(cmd => cmd.Destroy());
})
.Pageable()
.Scrollable(config => config.Enabled(false))
.Filterable(config => config.Mode(GridFilterMode.Menu))
.Sortable()
.Resizable(config => { config.Columns(true); })
.Reorderable(config => { config.Columns(true); })
.DataSource(source => source
.Ajax()
.PageSize(5)
.Model(model =>
{
model.Id(m => m.MemberId);
})
.Read(read => read.Action("FetchMemberLoanList", "Member", new { area = "AreaOne" }))
.Destroy(del => del.Action("Destroy", "Member", new { area = "AreaOne" }))
)
)
</div>
</div>
</div>
}
Related
Bootstrap form-group height growing
I have this control that the user can upload files. If the users upload more then 1 it runs into the next form-group control that is on this view. Is there a way I can get this form-group to grow? <div class="form-group row"> #Html.LabelFor(model => model.fileManagerIds) #(Html.Kendo().Upload() .Name("upImport") .HtmlAttributes(new { Style = "width: 700px;" }) .Messages(e => e.DropFilesHere("Drop files here") .Select("Select file")) .Async(a => a .Save("Async_Save", "Upload") .Remove("Async_Remove", "Upload") .AutoUpload(true) .SaveField("files") ) .Events(e => e.Success("upImportSuccess")) ) #Html.HiddenFor(x => x.fileManagerIds, new { id = string.Format("fileManagerIds"), #name = "fileManagerIds" }) </div>
Cypress problems take value and compare it. Scope variable
I have this HTML structure: <tr id="post-7053" class="iedit author-other level-0 post-7053 type-poi status-publish hentry webmapp_category-corbezzolo" data-id="7053"> <th scope="row" class="check-column"> <label class="screen-reader-text" for="cb-select-7053"> Seleziona 594 </label> <input id="cb-select-7053" type="checkbox" name="post[]" value="7053"> <div class="locked-indicator"> <span class="locked-indicator-icon" aria-hidden="true"></span> <span class="screen-reader-text"> “594” è bloccato </span> </div> </th> <td class="5da0bb937bd9f column-5da0bb937bd9f has-row-actions column-primary column-postid" data-colname="ID">7053 I have to take the value of an ID and compare it on another site: i have to get the first table id i managed to get it with this cypress command: id = cy.get('tbody#the-list td').first().invoke('val') only that when I go to compare the value of the variable id. it never enters the if branch. While if I put a value like 7156 or other it enters the if branch and makes the comparison. below the test code: describe('Registration', () => { const email = 'nedo#go.br' const password = 'pedhu' var id it('create new Nedo', () => { cy.visit('https://test.nedo/wp-admin') cy.get('input[name=log]').type(email) cy.get('input[name=pwd]').type(password) cy.get('input#wp-submit').click() cy.visit('https://test.nedo/edit.php?post_type=nedo') id = cy.get('tbody#the-list td').first().invoke('val') }) it('id', () => { cy.visit('https://nedostaging.z.hu/login') cy.get('input[name=email]').type('team#nedo.hi') cy.get('input[name=password]').type('nedo') cy.get('button').contains('Login').click() cy.get('#hometable > tbody > tr > td:nth-child(4)').each(($e, index, $list) => { const text = $e.text() cy.log(id) if (text.includes(id)) {//if I put a number instead of id it works assert.strictEqual(text, '{"id":'+id+'}', 'id nedo ok') } }) }) cy.log(id):
For handling same-origin policies, you can write "chromeWebSecurity": false in your cypress.json file. But this will only work with the chrome browser. describe('Registration', () => { const email = 'nedo#go.br' const password = 'pedhu' before(() => { cy.visit('https://test.nedo/wp-admin') cy.get('input[name=log]').type(email) cy.get('input[name=pwd]').type(password) cy.get('input#wp-submit').click() cy.visit('https://test.nedo/edit.php?post_type=nedo') cy.get('tbody#the-list td').first().invoke('val').as('id') }) it('id', () => { cy.visit('https://nedostaging.z.hu/login') cy.get('input[name=email]').type('team#nedo.hi') cy.get('input[name=password]').type('nedo') cy.get('button').contains('Login').click() cy.get('#id').then((id) => { cy.get('#hometable > tbody > tr > td:nth-child(4)').each(($e, index, $list) => { const text = $e.text() cy.log(id) if (text.includes(id)) { //if I put a number instead of id it works assert.strictEqual(text, '{"id":' + id + '}', 'id nedo ok') } }) }) }) })
How to filter dropdownlistfor according to what has selected in first dropdownlist in asp mvc?
I am working on a asp.net mvc project and I need to filter dropdownlist according to what user has selected first dropdownlist This is my first dropdownlist in view: <div class="form-group"> #Html.LabelFor(m => m.BuildDefinitionName, "Build Definition name", new { #class = "col-md-2 control-label" }) <div class="col-md-10"> #Html.DropDownListFor(m => m.BuildDefinitionName, new SelectList(Model.BuildData.Select(x => x.Key), "BuildInfo"), "select", new { #class = "form-control" }) </div> </div> and this is my second dropdownlist: <div class="form-group"> #Html.LabelFor(m => m.CurrentBuildNumber, "Current Build", new { #class = "col-md-2 control-label" }) <div class="col-md-10"> #Html.DropDownListFor(m => m.CurrentBuildNumber, new SelectList(Model.BuildData .Where(x=>x.Key == "#BuildDefinitionName") .Select(y => y.Value), "BuildInfo"), "select", new { #class = "form-control" }) </div> </div> I have a dictionary that key is string (what the user should chose first dropdown ) and value is IEnumerable ( what it should be filtered by the first dropdown selection). I am so thanksful for solving my problem. after applying the answer :
You need to use jquery to modify the second dropdown list. In your 2nd dropdown list, you need to put all the data of Model.BuildData. So, in your controller, be sure to provide all the records because we will be filtering on client-side. public ActionResult ControllerName(){ var yourModel = new yourModel(); // Add all the entries to Build Data, we're going to filter it with jquery yourModel.BuildData = db.BuildData.ToList(); return View(yourModel); } In your 2nd dropdown list, we need to put a data attribute on the html. For this example, we're rendering it manually, replace your 2nd dropdown list with the HTML below. <div class="form-group"> #Html.LabelFor(m => m.CurrentBuildNumber, "Current Build", new { #class = "col-md-2 control-label" }) <div class="col-md-10"> <select id="CurrentBuildNumber" name="CurrentBuildNumber" class="form-control"> #foreach(var selectItem in Model.BuildData){ <option data-filter="#selectItem.Key" value="#selectItem.Value"> #selectITEM.Value </option> } </select> </div> </div> Lastly, we need to add an onchange script to the 1st dropdown list that would filter the 2nd dropdownlist. The code below will loop through all the options in the 2nd dropdown list, and if its data-attribute doesn't match with the selected value, it will hide it. <script> $(document).ready(function(){ $(document).on("change","#BuildDefinitionName",function(){ var selected = $(this).val(); $("#CurrentBuildNumber").find("options").each(function(){ if($(this).data("filter")==selected){ // if data-filter is the same as the selected value, show it $(this).show(); }else{ // if it doesn't match, hide $(this).hide(); } }); }); }); </script>
Field positioning in mvc
I am trying to position these text fields next to each other and have them in the following format: (______) _____ - _____ My main problem is getting them to be next to each other. Does anybody have any suggestions on what I should do? Here is the code I have so far: <label style="margin: 5px" id="lblPhoneNumber">Phone Number (optional)</label> <p> #Html.ValidationMessageFor(model => model.Pharmacy.PhoneNumber) #Html.TextBoxFor(model => model.Pharmacy.AreaCode, new { style="width:3em", maxlength=3}) #Html.TextBoxFor(model => model.Pharmacy.PhoneNumberFirstThree, new { style="width:3em", maxlength = 3 }) #Html.TextBoxFor(model => model.Pharmacy.PhoneNumberLastFour, new { style="width:4em", maxlength = 4 }) </p>
It will be something like. You need to do it for all three textboxes: #Html.TextBox("Something", #Model.text, new {style = "display: inline-block;float:left"})
how to give #readonly in DropdownListfor in asp.net MVC 4? [duplicate]
What option do I need to set to make a drop down box readonly when using MVCs Html.DropDownList? I've tried things like.... Html.DropDownList("Types", Model.Types, new { _Enabled = "false" }) ...and many different things along this line; alas no joy! I thought this would be an easy.....and it probably is!
Try this Html.DropDownList("Types", Model.Types, new { #disabled = "disabled" })
Regarding the catch 22: If we use #disabled, the field is not sent to the action (Mamoud) And if we use #readonly, the drop down bug still lets you change the value Workaround: use #disabled, and add the field hidden after the drop down: #Html.HiddenFor(model => model.xxxxxxxx) Then it is truly disabled, and sent to the to the action too.
<script type="text/javascript"> $(function () { $(document) .ajaxStart(function () { $("#dropdownID").attr("disabled", "disabled"); }) .ajaxStop(function () { $("#dropdownID").removeAttr("disabled"); }); }); </script>
I had to disable the dropdownlist and hide the primary ID <div class="form-group"> #Html.LabelFor(model => model.OBJ_ID, "Objs", htmlAttributes: new { #class = "control-label col-md-2" }) <div class="col-md-10"> #Html.DropDownList("OBJ_ID", null, htmlAttributes: new { #class = "form-control", #disabled = "disabled"}) #Html.HiddenFor(m => m.OBJ_ID) #Html.ValidationMessageFor(model => model.OBJ_ID, "", new { #class = "text-danger" }) </div> </div>
A tip that may be obvious to some but not others.. If you're using the HTML Helper based on DropDownListFor then your ID will be duplicated in the HiddenFor input. Therefore, you'll have duplicate IDs which is invalid in HTML and if you're using javascript to populate the HiddenFor and DropDownList then you'll have a problem. The solution is to manually set the ID property in the htmlattributes array... #Html.HiddenFor(model => model.Entity) #Html.EnumDropDownListFor( model => model.Entity, new { #class = "form-control sharp", onchange = "", id =` "EntityDD", disabled = "disabled" } )
Or you can try something like this: Html.DropDownList("Types", Model.Types, new { #readonly = "true" })
Put this in style select[readonly] option, select[readonly] optgroup { display: none; }
I just do this and call it a day Model.Id > -1 ? Html.EnumDropDownListFor(m => m.Property, new { disabled = "disabled" }) : Html.EnumDropDownListFor(m => m.Property)
#Html.DropDownList("Types", Model.Types, new { #disabled = "" }) Works
Html.DropDownList("Types", Model.Types, new { #disabled = "disabled" }) #Html.Hidden(Model.Types) and for save and recover the data, use a hidden control
For completeness here is the HTML Helper for DropDownListFor that adds enabled parameter, when false select is disabled. It keeps html attributes defined in markup, or it enables usage of html attributes in markup, it posts select value to server and usage is very clean and simple. Here is the code for helper: public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled) { if (enabled) { return SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributes); } var htmlAttributesAsDict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); htmlAttributesAsDict.Add("disabled", "disabled"); string selectClientId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression)); htmlAttributesAsDict.Add("id", selectClientId + "_disabled"); var hiddenFieldMarkup = html.HiddenFor<TModel, TProperty>(expression); var selectMarkup = SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributesAsDict); return MvcHtmlString.Create(selectMarkup.ToString() + Environment.NewLine + hiddenFieldMarkup.ToString()); } and usage, goal is to disable select if there is just one item in options, markup: #Html.DropDownListFor(m => m.SomeValue, Model.SomeList, new { #class = "some-class" }, Model.SomeList > 1) And there is one even more elegant HTML Helper example, no post support for now (pretty straight forward job, just use HAP and add hidden input as root element sibling and swap id's): public static MvcHtmlString Disable(this MvcHtmlString previous, bool disabled, bool disableChildren = false) { if (disabled) { var canBeDisabled = new HashSet<string> { "button", "command", "fieldset", "input", "keygen", "optgroup", "option", "select", "textarea" }; var doc = new HtmlDocument(); doc.LoadHtml(previous.ToString()); var rootElements = doc.DocumentNode.Descendants().Where( hn => hn.NodeType == HtmlNodeType.Element && canBeDisabled.Contains(hn.Name.ToLower()) && (disableChildren || hn.ParentNode.NodeType == HtmlNodeType.Document)); foreach (var element in rootElements) { element.SetAttributeValue("disabled", ""); } string html = doc.DocumentNode.OuterHtml; return MvcHtmlString.Create(html); } return previous; } For example there is a model property bool AllInputsDisabled, when true all html inputs should be disabled: #Html.TextBoxFor(m => m.Address, new { placeholder = "Enter address" }).Disable(Model.AllInputsDisabled) #Html.DropDownListFor(m => m.DoYou, Model.YesNoList).Disable(Model.AllInputsDisabled)
You could use this approach Disabling all the options except the selected one: <select> <option disabled>1</option> <option disabled>2</option> <option selected>3</option> </select> This way the dropdown still submits, but the user can not select another value. With jQuery <script> $(document).ready(function () { $('#yourSelectId option:not(:selected)').prop("disabled", true); }); </script>
try with #disabled and jquery, in that way you can get the value on the Controller. Html.DropDownList("Types", Model.Types, new {#class = "your_class disabled", #disabled= "disabled" }) Add a class called "disabled" so you can enabled by searching that class(in case of multiples disabled fields), then you can use a "setTimeout" in case of not entering controller by validation attributes <script> function clickSubmit() { $("select.disabled").attr("disabled", false); setTimeout(function () { $("select.disabled").attr("disabled", true); }, 500); } </script> submit button like this. <button type="submit" value="Submit" onclick="clickSubmit();">Save</button> in case of inputs, just use #readonly="readonly" #Html.TextBoxFor("Types",Model.Types, new { #class = "form-control", #readonly= "readonly" })
You can set the select as readonly and then run some jquery to disable the options except the selected value. You cant change the value and it's included when the form is submitted. $(document).ready(function () { $('select option').removeAttr('disabled'); $('#readonlyTest').find('select[readonly] option').not('select[readonly] option[selected]').attr('disabled', 'disabled'); }); $('#submitButton').click(function(e) { var formData = $('form').serialize(); $('#formData').html(formData); }); body { margin: 50px; } <link href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form> <div class="form-group"> <label for="scopeReadonlyNoJs">Scope Readonly No Js</label> <select class="form-control" id="scopeReadonlyNoJs" name="scopeReadonlyNoJs" readonly="readonly"> <option value="">Select..</option> <option selected="selected" value="readonlyNoJsScopeValue1">Scope Value 1</option> <option value="readonlyNoJsScopeValue2">Scope Value 2</option> </select> <small id="scopeReadonlyNoJsHelp" class="form-text text-muted">This is read only and no js is applied. It looks disabled but you can change the values.</small> </div> <div id="readonlyTest" class="form-group"> <label for="scopeReadonly">Scope Readonly</label> <select class="form-control" id="scopeReadonly" name="scopeReadonly" readonly="readonly"> <option value="">Select..</option> <option selected="selected" value="readonlyScopeValue1">Scope Value 1</option> <option value="readonlyScopeValue2">Scope Value 2</option> </select> <small id="scopeReadonlyHelp" class="form-text text-muted">This is read only and is disabled via js by disabling the options except the selected one.</small> </div> <div class="form-group"> <label for="scopeDisabled">Scope Disabled</label> <select class="form-control" id="scopeDisabled" name="scopeDisabled" disabled="disabled"> <option value="">Select..</option> <option selected="selected" value="disabledScopeValue1">Scope Value 1</option> <option value="disabledScopeValue2">Scope Value 2</option> </select> <small id="scopeDisabledHelp" class="form-text text-muted">This is disabled and wont be posted.</small> </div> <button id="submitButton" type="button"> Submit </button> </form> <p id="formData"> </p>
I've create this answer after referring above all comments & answers. This will resolve the dropdown population error even it get disabled. Step 01 Html.DropDownList("Types", Model.Types, new {#readonly="readonly"}) Step 02 This is css pointerevent remove code. <style type="text/css"> #Types { pointer-events:none; } </style> Then you can have expected results Tested & Proven