Razor CheckBoxFor conditionally check and un-check in view - asp.net-mvc

In my view I have,
#Html.CheckBoxFor(m => m.IsExist, new { #id = "IsExist" })
In my Model I have IsExist value from DB. Either true or false.
Now how can I 'Check' or 'Uncheck' the option, based on the true or false value in IsExist.
I expected, on binding by default the check box takes the value of Model. Howeverr that is not happening.
How can i achieve it?

Here how i achieved it
#Html.CheckBox("VC",(item.isVC=="Y") ? true : false)
where my item.isVC has value "Y" or "N"

Below snippet indicates an alternate way of having checkbox created and conditionally making it checked/unchecked. The following approach is also useful to get the value of checkbox by traditional approach using jquery.
#model myproject.Models.StudentModel
<div class="row">
<label class="checkbox-inline">
<input type="checkbox" name="selfStudy" checked="#Model.IsExist"><b>Self Study</b>
</label>
</div>

You can do this to check a checkbox :
if (Model.IsExist) {
#Html.CheckBoxFor(m => m.IsExist, new { #id = "IsExist", "checked" = "checked"})
}
Hope it's help

Related

How to disable model view check box in .net mvc?

How to disable model view check box in .net mvc?
I tried with the syntax : new { disabled = "disabled" } but doesn't work.
<div class="col-sm-7 checkbox-inline text-left">
<label style="margin-right:15px"></label>
#Html.CheckBoxFor(model => model.Email, new { disabled = "disabled" } ) <label class="hthin" asp-for="Email" style="margin-right:30px"></label>
#Html.CheckBoxFor(model => model.Pager, new { disabled = "disabled" }) <label class="hthin" asp-for="Pager" style="margin-right:30px"></label>
#Html.CheckBoxFor(model => model.Landline, new { disabled = "disabled" }) <label class="hthin" asp-for="Landline" style="margin-right:30px"></label>
</div>
#Html.CheckBoxFor() - model object property should be boolean.
Thanks Stephen Muecke. I updated my answer. # symbol is used for reserved keywords. For example #class.
Thanks GregH. You catch it perfect.

RadiobuttonFor and nullable bool checked property issue

I have a MVC View Model in which I have nullable boolean property:
[DisplayName("Is Active")]
public bool? IsActive { get; set; }
View:
<div class="col-md-3">
<div class="row">
<label>#Html.LabelFor(model => model.IsActive)</label>
</div>
#Html.RadioButtonFor(model => model.IsActive, true, new {id = "IsIsActiveTrue" })
<label>Yes</label>
#Html.RadioButtonFor(model => model.IsActive, false, new {id = "IsIsActiveFalse" })
<label>No</label>
#Html.RadioButtonFor(model => model.IsActive, "", new {id = "IsIsActiveAll"})
<label>All</label>
</div>
By default, I would like to select All when page loads. I tried to add
#checked = "checked"
but it didn't work (any of radiobutton value is selected). Please advise.
You cannot pass NULL as the value for the radio button when using RadioButtonFor helper method. If you pass ""as the value, you cannot set that in your GET action as your variable type is bool?,not string.
If you absolutely want 3 radiobuttons with your current type, you may simply write pure HTML code to render that. As long as your radio button's name attribute value matches your view model property name, model binding will work fine when you submit the form.
#using (Html.BeginForm("Search","Customer"))
{
<label>Active</label>
<input type="radio" name="IsActive" value="true"/>
<label>In Active</label>
<input type="radio" name="IsActive" value="false"/>
<label>All</label>
<input type="radio" name="IsActive" checked="checked" />
<input type="submit"/>
}
Here we are setting the checked attribute for all in the HTML markup.
Another option is to switch your controls from 3 radio buttons to 2 checkboxes. You can mark all of them checked initially and user may select/unselect as needed. Another option is changing your type from bool? to an enum with these 3 values. With both of these approaches, with the use of CheckBoxFor or RadioButtonFor helper, you should be able to set the items which needs to be checked, in your GET action method. Use the one which is more appropriate to your code structure/style.
I did it by replacing RadiobuttonFor with RadioButton:
<div class="row">
<label>#Html.LabelFor(model => model.IsActive)</label>
</div>
<div class="row col-md-12">
#Html.RadioButton("IsActive", true, false) Yes
#Html.RadioButton("IsActive", false, false) No
#Html.RadioButton("IsActive", null, true) All
</div>

Disabled property not working for ListBoxFor and DropDownListFor

I have a web page that dynamically creates components by rendering them through a RenderPartial Html Helper like this
Html.RenderPartial("_UploadStaticField", config);
Within the config object is a field called 'isUnderReview'. When this is set to true the components should be disabled by using the code below
//Single selection
<div class="editor-section">
<div class="label">
#Html.DisplayEditLabel(Model.Label, Model.Required.Value)
</div>
<div class="field large-text-field">
#Html.DropDownListFor(m => m.SelectedListOptionID, new SelectList(Model.ListOptions, "ID", "Name", Model.SelectedListOptionID).OrderBy(l => l.Value), new Dictionary<string, object>{
{"id", "staticField_" + Model.ID}})
</div>
</div>
<script>
$(document).ready(function () {
if ("#Model.IsUnderReview" == "True") {
document.getElementById("staticField_" + "#Model.ID").disabled = true;
}
});
</script>
and..
//Multiple selection
<div class="editor-section">
<div class="label">
#Html.DisplayEditLabel(Model.Label, Model.Required.Value)
</div>
<div class="field large-text-field">
#Html.ListBoxFor(x => x.SelectedRoles, filetypes, new { #class = "multiselectFileTypes" , id = "staticFieldM_" + Model.ID})
</div>
</div>
#Scripts.Render(BundleConfig.Scripts_MultiSelect)
<script>
$(document).ready(function () {
if ("#Model.IsUnderReview" == "True") {
document.getElementById("staticFieldM_" + "#Model.ID").disabled = true;
}
});
</script>
The code works to the point that the methods run but the components are still able to be used. Is there a way of cancelling any users selections which will serve as disabling as the values wont change?
Scripts should never be in partials (you potentially generating multiple inline scripts that may cause other problems, especially with the bundle). However a script is not even necessary for this, you can use a simple if statement or conditional attributes to generate what you want.
When you say "but the components are still able to be used", I'm guessing that your using a plugin to generate controls as suggested by Scripts.Render(BundleConfig.Scripts_MultiSelect) which will be hiding the original <select> element and generating its own html which is why it still interactive.
But the next problem is that disabled controls do not post back a value, so the vales of SelectedListOptionID and SelectedRoles will be their default, possibly resulting in your app failing depending on the code in your POST method.
Move the #Scripts.Render() into you view or layout, delete the scripts to disable the element and then change the partial to
#if(Model.IsUnderReview)
{
#Html.HiddenFor(m => m.SelectedListOptionID) // if you want the value to be posted
// add an element to display the Name associated with the SelectedListOptionID
// if necessary, for example your view model might include a property
// string SelectedListOptionName
}
else
{
#Html.DropDownListFor(m => m.SelectedListOptionID, new SelectList(Model.ListOptions, "ID", "Name").OrderBy(l => l.Value))
}
Side notes:
There is no reason to add you own id attribute (the
DropDownListFor() method generates <select
id="SelectedListOptionID" ... >
Remove the last parameter of the SelectList constructor
(Model.SelectedListOptionID) - its ignored by the
DropDownListFor() method. I also recommend your model contains an IEnumerable<SelectListItem> OptionsList property and you populate that in the controller so that it can simply be #Html.DropDownListFor(m => m.SelectedListOptionID, Model.OptionsList)

How to pass dropdown list selected value in knockout function?

I have to pass the dropdown selected value in knockout function. I have crated the razor syntax for that:
<div class="row">
#Html.LabelFor(m => m.FilterByType, htmlAttributes: new { #class = "label" })
#Html.DropDownListFor(m => m.FilterByType, new SelectList(Model.aspNetUser, "FilterByType", "FilterByName"), new { #class = "selectBox", #id = "aspnetUsersType", #data_bind = "event: {change: getData(0,'','',size,index,'')}" })
<input type="hidden" id="filterByType" name="filterByType" value="">
</div>
Following is my knockout function:
self.getData = function (filterbytype, fromdaterange, todaterange, pageSize, page, searchText) {"some task"}
How do I pass the selected value in the getData? Right now I am passing 0 as a filterbytype.
The objects can be passed from server to client using JSON, and binded to a property of type observableArray. Then bind this property to a html element using foreach binding. You can see an example here:
http://knockoutjs.com/documentation/foreach-binding.html
Suppose are using this following code in ur HTML
<select data-bind="options: operations, value: self.selectedOperation">
Make sure that You must be using these variables as ko.observable() type
so ur JS code will look like this
var self = this;
self.selectedOperation = ko.observable("Option1"); // with self u can use more variables and here selectedOperation will be containing the choosen value you want and you can pass it wherever u want
var operations = ko.observableArray(["Option1", "Option2", "option3", "Opt4"]); // dropdown List
Now its up to you how you are going to use that variable..

MVC Radiobutton default value did not set after knockout data-bind

I am using MVC strongly typed view to generate two radio buttons
<div>
#Html.LabelFor(model => model.Eligible)
#Html.RadioButtonFor(model => model.Eligible,"true", new { id="yes", data_bind = "checked: completeVM.Eligible " })
#Html.Label("yes", "YES")
#Html.RadioButtonFor(model => model.Eligible, "false", new {id="no", data_bind = "checked: completeVM.Eligible " })
#Html.Label("no", "No")
</div>
If I don't use data_bind, when the page loads, the 'No' radio button will be set by default. But after I add data_bind, neither radio button is checked. I noticed in my view model, the Eligible was displayed as :"Eligible": false; if I check 'No' button, it will display as "Eligible":"false". How can I fix this so that when the page loads, the 'No' button will be checked by default. Thanks
This is a common problem. Radio button values are always a string. Yet you want boolean behavior. The easiest fix is to use an extra computed observable to do the translation for you:
Assuming 'this' points to your viewmodel:
this.EligibleRadioHelper = ko.computed({
read: function () {
return this.Eligible().toString();
},
write: function (value) {
this.Eligible(value === 'true');
},
owner: this
});
Bind against this new helper:
data-bind="checked: completeVM.EligibleRadioHelper"
When you want the boolean value (for logic or for persisting) use your original observable.
You also can try using the checkedValue binding available in knockout 3 without the need to write a computed function for your view model.
Your code will become something like this:
<div>
#Html.LabelFor(model => model.Eligible)
#Html.RadioButtonFor(model => model.Eligible,"true", new { id="yes", data_bind = "checked: completeVM.Eligible, checkedValue: true" })
#Html.Label("yes", "YES")
#Html.RadioButtonFor(model => model.Eligible, "false", new {id="no", data_bind = "checked: completeVM.Eligible, checkedValue: false " })
#Html.Label("no", "No")

Resources