Conditionally disabling a Bootstrap control - c#

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.

Related

How to take value from DataValueField() of a Kendo().DropDownList() on change event

I'm using kendo grid and editor template for showing my data. in editor I've given id to DataValueField() and name to DataTextField() of kendo dropdown list. In change event, I'm not able to get the DataValueField(). see the following code
This is my editor template MemoCarrier.chtml
#using System.Collections
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
.Events(e =>
{
e.Change("MemoCarrier");
})
)
Here is my on change function
function MemoCarrier(e) {
var AirlineName = this.value();
alert(AirlineName) //it displays PARTNERNAME instead of PARTNERID
}
Currently I'm getting name ie;DataTextField() value. instead of that, I need DataValueField().
Thanks for suggestions in advance!
so based on your comment the easiest way to do this would probably use the data-bind attribute to simplify the process of binding the model. Assuming you are using the MVC helper for the grid as well.
so taking your code and adding this:
#(Html.Kendo().DropDownList()
.DataValueField("PARTNERID")
.DataTextField("PARTNERNAME")
.Name("AIRLINENAME")
.BindTo((IEnumerable)ViewBag.lstAirline)
.HtmlAttributes(new { maxlength = "", #class = "MNum", data_bind="value:{yourProperyNameHere}" })
.OptionLabel("-Select-Flight ")
.Filter(FilterType.Contains)
)
So hopefully you can see all I am doing is adding a new HtmlAttribute property to the control for you. All you need to do is put whatever property is meant to be the value for this.
Depending on if this value is a complex (object) or simple (string, int etc) primitive type you may need to set the Primitive property to true so that only the valuefield e.g the id you are assigning is bound back to the grid's row model.

How to get disabled DropDownList control value to controller

Work on asp.net mvc5.My project DropDownList work perfectly problem arise when i disabled DropDownList control then can not get value in controller.
My razor syntax is bellow:
<div class="form-group">
#Html.LabelFor(m => m.ProductName, new {#class = "col-md-3 control-label"})
<div class="col-md-3">
#Html.DropDownList("ProductID", null, "Select product", new {#placeholder = "Select product", #class = "form-control", #disabled = "disabled" })
</div>
</div>
my controller syntax to fill the above DropDownList
private void LoadProductsInViewData(object selectedValue = null)
{
var datas = productRepository.GetAll().OrderBy(p => p.Name);
ViewBag.ProductID = new SelectList(datas, "ProductID", "Name", selectedValue);
}
Why In controller create/edit event can not get the DropDownList value?
Note:I know it's disabled control default behavior,i try to use hidden column like this.Problem is how hidden column used with my approach.
You can use Jquery to retrive the value of Currently Selected item of DropList which is disabled in your case, using
var dropDownValue=("#Id_of_u_Dropdownlist").val()
and you can send the DropDownValue variable which contains value of Disable Dropdown list to Controller.
This is a normal behavior. Disabled fields cannot be posted, then it's a common pratice to add a Html.HiddenFor() to post the disabled value.
As you said, there is no "ProductId" property in your model. However, if you create a Html.Hidden("ProductId", "YourValue") and add a parameter named 'productId' in your Controller Create/Edit action, the value should be subimitted.
Create an Httpost Action and then use FormCollection Object like this
[HttpPost]
public ActionResult GetDropDownValue(FormCollection Form)
{
string dropdownValue=form["ID_of_dropdownlist"].toString();
}

Input value does not show up in MVC

I am trying to populate textarea using the input value. But it is not working. Any solution to this issue?
#Html.EditorFor(model => model.ModelName, new { htmlAttributes = new { #class = "textbox-css", #Value = "ViewData.Model.ModelName" } })
You can remove quotes from #Value = "ViewData.Model.ModelName", because you are sending a string to Value property, not the content of ModelName property.
But why don't you use the TextArea helper? Like:
#Html.TextAreaFor(model => model.ModelName, new { htmlAttributes = new { #class = "textbox-css" })
It's not common set the value property like you are doing, I don't know if it works, actually. I think this is not a good way to do that. You should use the TextAreaFor(x => x.Property) or EditFor(x => x.Property) directly, instead of set the value property, as I said.
you don't need to manually populate the value property with the ViewData, remove the #Value = "ViewData.Model.ModelName". I think the problem is your ViewData name conflict with the property of the model (both have the name "ModelName").
Try changing the ViewData property name to something else. Works for me when I have an issue with unpopulated DropDownListFor

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.

ASP.NET MVC 3: Override "name" attribute with TextBoxFor

Is it possible when using Html.TextBoxFor to override the name attribute?
I have tried with no success. I need to use TextBoxFor to get client side validation to work, however for reasons I won't go into I need the name of the textbox to be different from the generated one.
I have tried the following:
#Html.TextBoxFor(x => x.Data, new { name = Model.Key + "_Data", id = Model.Key + "_Data" })
Which works for ID but not name. Is this possible?
Update: Looking into the code for TextBoxFor. It doesn't look like there is an easy way. Hopefully someone can prove me wrong.
Rob, actually there is a much simpler way. Instead of name, use Name:
#Html.TextBoxFor(x => x.Data, new { Name = Model.Key + "_Data", id = Model.Key + "_Data" })
Are you asking this because you want to apply a prefix to the name? If so, you can do this by setting ViewData.TemplateInfo.HtmlFieldPrefix in your Controller.
I learnt a lot about this stuff from Brad Wilson's blog.
EditorFor has an overload where you can supply the name attribute as a parameter:
#Html.EditorFor(expression, null, name)
Try EditorFor. you can pass string as template name if you want to make sure textbox is rendered even if property type is not string. If property is string already, it does not need templatename explicitly to render textbox, so you can pass null. Note that it does not require id parameter explicitly, it will infer it from element name. And all the validation things are still active with EditorFor
#Html.EditorFor(x => x.Data, "string", Model.Key + "_Data")
It is called Microsoft GOTCHA...
Use the name in caps, like this
#Html.TextBoxFor(m => m.Reply.Answer, new { Name = "Whatyouwant" })
ben's answer got me what I was looking for except you need to wrap in in Html.Raw
#Html.Raw(Html.TextBoxFor(x => x.Data).ToString().Replace("Data", "NewData"))
a little bit "unpretty"=), try:
#Html.TextBoxFor(x => x.Data).ToString().Replace("Data", "NewData")
For me, it works! I hope that help!
#Html.EditorFor(model => model.Nome, new { htmlAttributes = new { #class = "form-control", #maxlength = "80", #id = "NomeFilter", #Name = "NomeFilter" } })
#Html.EditorFor(Model => Model.Something, "name", "name", new {#class = "form-control" })
Not sure which of those two string parameters in the middle do the work, but it worked only when I typed both of them.
For this example, I was disabling form fields based on permissions, but still showing them. I had a hidden field to send the value to the controller, but wanted a different field name in the EditorFor.
First param after model value represents the "name" property, second is the new name.
#Html.EditorFor(m => m.UserName, "name", "UserNameDisabled", new { htmlAttributes = new { #class = "form-control", #disabled = "disabled"} });
Results in:
<input class="form-control text-box single-line" disabled="disabled" id="UserNameDisabled" name="UserNameDisabled" type="text" value="someEnteredValue" />
Keep it simple, your already providing the ID you should simply be able to use the method "TextBox" instead of "TextBoxFor" and it will work fine client side and server side. In addition, although the accepted answer will work but will produce duplicate Name attributes on your tag if you inspect it using a browser. The below solution does not have that problem.
MvcHtmlString Html.TextBox(string name, string value, object htmlAttributes)
#Html.TextBox(Model.Key + "_Data", Model.Key, new { id = Model.Key + "_Data" }

Categories

Resources