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")
Related
How do I specify the Value that should be entered into the Textbox. I dont want to use dropdownlist. I want to accept only these three (3) values Nigeria, Ghana and Togo
If any other value is entered it should not save or hide or disable the Save button.
View
<div class="col-md-12">
<div>
#Html.LabelFor(model => model.COUNTRY_NAME, "Country Name")
#Html.TextBoxFor(model => model.COUNTRY_NAME, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = "Country Name", #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.COUNTRY_NAME, null, new { #class = "text-danger" })
</div>
</div>
Please how do I achieve this?
There are two Options
You can use Server side Custom Validator for Country_Name property.
Or Jquery validation on client side.
When you submit the form, you can validate textbox value by jQuery.
<button onclick="validateData();"></button>
Then write a validation method as follows.
function validateData() {
if (Nigeria, Ghana and Togo) {
//ajax post to your controller
} else {
//return error message
}
}
I have below code and I want to change label text base on selected role.
For example, If I select Admin then in label Text I need "Admin Name" etc.
I use below code but I is not working.
<div class="editor-field">
#Html.DropDownListFor(model => model.RoleID, new SelectList(ViewBag.RoleLsit, "Id", "RoleName"), "Select Category", new { onchange = "SelectedIndexChanged()" })
</div>
<div>
#Html.LabelFor(model => model.RoleName)
#Html.EditorFor(model => model.RoleName)
#Html.ValidationMessageFor(model => model.RoleName)
</div>
<script type="text/javascript">
function SelectedIndexChanged() {
var sub = document.getElementsByName("RoleName");
sub.value = "Selected Role Name";
}
Thanks
You could find your elements using #Html.IdFor, if your js is in your view.
function SelectedIndexChanged() {
//find the label
var label = document.querySelector('label[for="#Html.IdFor(m => m.RoleName)"]');
//get the dropDown selected option text
var dropDown = document.getElementById("#Html.IdFor(m => m.RoleId)");
var selectedText = dropDown.options[dropDown.selectedIndex].text;
//set the label text
label.innerHTML=selectedText
}
By the way, taking a look a jQuery might be an "interesting" option.
You could simply remove the new { onchange = "SelectedIndexChanged()" , then
$('##Html.IdFor(m => m.RoleId)').change(function() {
$('label[for="#Html.IdFor(m => m.RoleName)"]').text($(this).children('option:selected').text());
});
function SelectedIndexChanged() {
document.getElementsById("RoleName").InnerHtml="Role name goes here";
}
you should use get element by id instead of name because when this html helper renders the strongly typed binded attributes becomes the id of that control . so in your case role name will be the ID
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..
I have a kendo window which I want to populate depending on a selection made in a dropdown. I've tried refreshing the window upon open, but I can't figure out how to make that work. Changing gears, I'm wondering if I can instead send a variable parameter to the controller within window declaration itself, and then do a simple window.refresh (instead of coding the refresh to hit a specific controller, which isn't working).
I mean something like this:
#(Html.Kendo().Window()
.Name("EditWindow")
.Title("Edit Contact")
.LoadContentFrom("_ContactEdit", "Contacts", new { selectedContact = $("#ContactId").data("kendoComboBox").value() })
.Content("Loading...")
.Visible(false)
.Draggable()
.Resizable()
.Width(400)
.Modal(true)
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
)
Or this:
#(Html.Kendo().Window()
.Name("EditWindow")
.Title("Edit Contact")
.LoadContentFrom("_ContactEdit", "Contacts", new { selectedContact = getContact() })
.Content("Loading...")
.Visible(false)
.Draggable()
.Resizable()
.Width(400)
.Modal(true)
.Actions(actions => actions.Pin().Minimize().Maximize().Close())
)
Obviously neither of these work, but I'm wondering if there's another way to fill in this field?
Thank you!
edit: Adding relevant code from controller and window/partial view. My controller is now being hit, but my window is not pulling the correct data. Any ideas?
Window:
#model [taking out company info].Contact
#using Kendo.Mvc.Extensions
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset id="infoForm">Hello, world.
#Html.HiddenFor(model => model.ContactId, new { id = "EditWindowId" })
<br />
<label id ="ContactNameID" style="width: 130px;">Contact Name</label>
<span>
#Html.TextBoxFor(model => model.FullName, new { type = "text", id = "EditWindowName", #class = "k-textbox form-control", style = "width: 200px; cursor:default" })
</span><br />
</fieldset>
}
Controller:
[HttpGet]
public ActionResult _ContactEdit(int selectedContact)
{
var entities = from r in dbContext.Contacts
where r.ContactId == selectedContact
select r;
if (entities.Any())
{ return PartialView(entities.First()); }
else
{ return HttpNotFound("Contact does not exist."); }
}
You can leverage the change event of your dropdown list to grab the selected value. Once you have the selected value you can programmatically refresh the window with the appropriate action on your controller. For example, the code below defines a Kendo DropDownList with a subscription to the change event. In the change, the value is used to build a dynamic url, and the kendo window is refreshed with that url:
<%= Html.Kendo().DropDownList()
.Name("dropdownlist")
...
.Events(e =>
{
e.Change("onChange")
})
%>
<script type='text/javascript'>
function onChange(){
var value = this.value(),
window = $("#EditWindow").data("kendoWindow");
window.refresh({
url: "/Contact/_ContactEdit?selectedContact=" + value
});
}
</script>
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