set a radio button selected by defualt in Html.RadioButtonFor - view

I can not select a default option for my radio buttons in my view.
I have tried:
#Html.RadioButtonFor(s => s.Before, false, new { #checked = true })
#Html.RadioButtonFor(s => s.Before, false, new { #class = "checked" })
and many other ways - but none of them is working!
and also I like to make it required. How can I make it selected and required?
I am using .NET Core 5.

How to make it selected:
The radio button will be checked if the value of property in the model is equal to the second argument we pass in to RadioButtonFor method.
So, in your case if you set Before property to false, then the radio button will be checked. I guess the right way would be set the value of Before to true and pass true as second argument value.
To make it require:
Decorate the Property with "System.ComponentModel.DataAnnotations.RequiredAttribute" attribute which makes the property required. Now you can check this.ModelState.IsValid in the post method and return this.Page().
Note: The page can be validated at client side if you use
jquery-validation library.
In case of bool types they will always have either true or false so
the model will always be valid even user won't select it. In this case
use nullable bool instead of bool.
[BindProperty]
[Required]
public bool? Before{ get; set; }
In the get method
this.Before = true;
In the view
#Html.RadioButtonFor(s => s.Before, true)
Please let me know if that works.

Related

add command to check text and attribute

I have to write a command where i have a textfield which should have a value and i have to check that the field is disabled or not. The disabled part can be case per case that is sometimes i do not need this assertion but the value check will always be there.
This is what i have done so far:
Cypress.Commands.add('checkTextAndAttr', (selector, value) => {
cy.get(selector).within(() => {
cy.get('input').should('have.value', value)
})
This is the html of a disabled button:
<input disabled="" placeholder="my-field" type="tel" value="0,00" inputmode="numeric">
and this for one which is enabled:
<input placeholder="my-field" type="tel" value="1 200,00" inputmode="numeric">
A field which is enabled is a field in which i can input text.
A field not enabled is one which cannot input text, when a calculation is done the field will be updated by itself.
How do i put the disabled condition in it?
thank you
I think the best way would be to add an additional parameter to your command. We can then use that parameter to conditionally change the assertion between 'have.attr' and 'not.have.attr'. Below, I'm using a ternary to accomplish that.
Cypress.Commands.add('checkTextAndAttr', (selector, value, isDisabled) => {
cy.get(selector).within(() => {
cy.get('input').should('have.value', value);
cy.get('input').should(isDisabled ? 'have.attr' : 'not.have.attr', 'disabled')
});
});
Additionally, if you had an overwhelming amount of one checks vs. the other, you could make the isDisabled parameter optional/nullable, and make that "default" check the false result of the ternary. (If switching 'have.attr' to the false statement, it may make sense to rename isDisabled to isEnabled)
Cypress.Commands.add('checkTextAndAttr', (selector, value, isDisabled?)
// with isDisabled false
cy.checkTextAndAttr('foo', 'bar', false);
// with isDisabled true
cy.checkTextAndAttr('foo', 'bar', true);
// with isDisabled undefined -- the `.should()` evaluates the same as false (both undefined and false are not true)
cy.checkTextAndAttr('foo', 'bar')

HandsOnTable Dropdown Without Editable Text?

Is it possible to use a dropdown column in a HandsOnTable without the editable textbox?
I know you can set the type to dropdown and it will validate/highlight red when you enter an invalid value, but is there a way to completely disable text entry for dropdown columns? It seems just using the readOnly property on the column blocks the dropdown altogether.
As you said, the readOnly option will disable you dropdown. So I believe the closest solution you can use is the allowIndvalid = false (true by default) :
allowInvalid: true (optional) - allows manual input of value that does not exist in the source. In this case, the field background highlight becomes red and the selection advances to the next cell
allowInvalid: false - does not allow manual input of value that does not exist in the source. In this case, the ENTER key is ignored and the editor field remains opened.
Documentation Link
You can use this JSFiddle to quickly check this option
I have the same issue and was able to resolve it with such steps. Maybe this could help:
1 when creating columns add a special className to the necessary column type:
{
data: 'priceUnitsName',
type: 'dropdown',
invalidCellClassName: 'colored',
source: Object.keys(unitNames),
width: 100,
className: 'disable-edit',
}
2 Subscribe to events to handle cancel editing:
private targetCell: HTMLTableCellElement;
public settings: GridSettings = {
// your settings
afterOnCellMouseDown: (event: MouseEvent, coords: CellCoords, TD: HTMLTableCellElement) => {
this.targetCell = TD;
},
afterBeginEditing: (row: number, column: number) => {
if (this.targetCell.classList.contains('disable-edit')) { // this handle only necessary columns with special class
setTimeout(() => {
const inputCollection: HTMLCollection = document.getElementsByClassName('handsontableInput');
Array.from(inputCollection).forEach((input: HTMLTextAreaElement) => {
input.blur(); // this calls blur on element manually
});
});
}
},
Maybe this is not the best decision, but by default, handsontable can't make dropdown elements readonly with leaving open-close dropdown functional and I can't find any workable suggestion with this.
Checked on 'dropdown' and 'date' types, and it works.

C# DataGridView Event to Catch When Cell (ReadOnly) Value has been changed by user

I have a Winforms app written in C#.
In DataGridView, I have set a column(DataGridViewTextBoxColumn) called 'Name' to ReadOnly = true.
When the user right click on a Cell of the 'Name' column -> Display a form to set a value -> I want the application to know: Cell's value of the 'Name' column has been changed.
I have tried many events but can not do, such as CellEndEdit, CellValueChanged
I'm only interested in catching user changes to data in the 'Plan' column where ReadOnly = true.
Which is the best event to use for this?
I attach information as below:
① Image Description
② Source Code
The CellEndEdit and CellValueChanged properties only work when the user changes manually the content of the DataGridView. What you have to do is just to read the value of the TextBox in the Set_Value_Of_Name form and compare it with the value of the DataGridView cell.
Add the following line :
btnOK.Click += (senderq, eq) =>
{
frmValueOfName.Close();
result = true;
//Add this line
if (txtValue.Text != dataGridView[currentMouseOverCol,currentMouseOverRow].Value.ToString())
{
MessageBox.Show("Value has been changed!");
}
};

MVC 3 Bind Model property to 2 fields (e.g. Other Title)

I'm trying to achieve a very common scenario whereas given a list of options to choose from, the last one says "Other" and when selected the user is presented with the input field to specify what "other" is.
In my case, it's a list of Person's titles:
public List<string> TitleList
{
get
{
return new List<string> { "Mr", "Mrs", "Miss", "Dr", "Other" };
}
}
and what I'm trying to do is this:
#Html.DropDownListFor(m => m.Title, new SelectList(Model.TitleList), "Please select...") #Html.TextBoxFor(m => m.Title)
I want the model to bind the TextBox value when "Other" is selected in the DropDownLis, and bind to selected item in DropDownList in all other cases.
Is this achievable without adding an extra property on the Model?
a better solution is not to bind to two fields, instead, copy selected item from a drop-down into bound textbox with some clever javascript:
#Html.DropDownList("ddlTitle", new SelectList(Model.TitleList), "Please select")
#Html.TextBoxFor(m => m.Title, new { maxLength = 10 })
Javascript:
ToggleTitleFields = function () {
var title, txtTitle;
title = $('select#ddlTitle').val();
txtTitle = $('input#Title');
if (title === "Other") {
txtTitle.val("");
txtTitle.show();
return txtTitle.focus();
} else {
txtTitle.hide();
txtTitle.val(title);
return $('span[data-valmsg-for="Title"]').empty();
}
};
$(document).on("change", "select#ddlTitle", function(e) {
return ToggleTitleFields();
});
hope this helps somebody
found a client-side solution: add/remove the "name" attribute from DropDownList. Here's my coffee script:
ToggleTitleFields = () ->
if $('select#Title').val() == "Other"
$('select#Title').removeAttr('name')
else
$('select#Title').attr('name','Title')
Tsar,
Being honest, this isn't a scenario that I've had to deal with before, but is nonetheless a good one. If I were faced with this dilemma and was allowed to use a javascript solution, i'd present a previously 'hidden' textbox when other was chosen. The user would then have to enter the new value into this texbox, which on loosing focus would populate the selectlist and be selected. Then when the form was submitted, you'd have this new value still as part of the exisiting model.
Of course, you could also do a similar logic of showing the textbox when selecting other but this time, do a little logic on the httpost controller action to determine if the 'other' item was selected and then populate the model from the 'textbox' value.
Of course, both scenarios would need a heap of validation, but in principle, either approach would 'work'

Knockout checked binding issue

I'm having a problem with checkbox bindings not quite working with KnockoutJS 2.0. I have an array of objects. One of the properties of those objects is an array of different objects. In the child objects there are a few properties, one of which is a boolean. I build a list for each parent object and under each parent I show the children. For each list of children I have two views, a read only and an edit view. In the read only I have images that represent whether or not the item is checked based on the boolean property. This works and if I update the boolean value through the console, I'm seeing what I would expect--the image goes away or displays based on the value I assign. In the edit view, the images are replaced with a checkbox. I see the same behavior when I update the value through the console--it is checked when I expect it to be and not when I don't. The problem comes in when I check or uncheck the checkbox. Doing this doesn't change the underlying value the checkbox is bound to.
Here's the basic idea of my data.
[
{
"xxx": "yyy",
"xxx": "yyy",
...
"Displays": [
{
"xxx": "yyy",
...
"Excluded": false,
},
{
"xxx": "yyy",
...
"Excluded": true,
}
],
}
]
Here's the binding
<input type="checkbox" data-bind="checked: !Excluded()" />
the problem is that "checked" here is a bidirectional binding: the bound property needs to be read to generate the correct view, but needs also to be updated when you click on the checkbox. Contrast this to a binding like:
<span data-bind="text: 'your name is ' + name()"></span>
when the expression is only read, so you can use an expression (and you need to unwrap the observable).
So, you need to bind directly to the observable property, without "unwrapping" it adding '()', it will be done by knockout when needed, both for read and write:
<input type="checkbox" data-bind="checked: Excluded" />
See http://jsfiddle.net/saurus/usKwA/ for a simple example. Note how the checkbox labels are updated on change, showing that the model is updated and the rendering triggers correctly.
If you need to negate the value (so that the checkbox is checked when the value is false), you can add a writeable computed observable, as explained on http://knockoutjs.com/documentation/computedObservables.html section "Writeable computed observables", or you can negate the data in the viewmodel, doing it on the server just before sending the data, or on the client before populating the viewmodel.
hope this helps.
I know my answer is a bit late to the game here, but I had this problem today and this was the closest thread I could find related to the problem, and it doesn't seem to have an answer that solves it. So here's my solution.
Essentially, the issue is that knockout really wants your viewModel values to be a string, not a boolean, but this isn't always practical. So, I created a binding called "isChecked" which works strictly with booleans. Note: This will only work with observable properties.
ko.bindingHandlers.isChecked = {
getElementDeclaredValue: function (element) {
var declaredValue = element.getAttribute("value");
// If a value is provided, we presume it represents "true",
// unless its explicitly "false". If no value is provided, we
// presume that a checked state would equal "true".
return declaredValue && Boolean.isBool(declaredValue)
? Boolean.parse(declaredValue)
: true;
},
init: function (element, valueAccessor) {
var updateHandler = function () {
var declaredValue = ko.bindingHandlers.isChecked.getElementDeclaredValue(element);
var elementValue = element.checked ? declaredValue : !declaredValue;
var modelValue = valueAccessor();
var currentValue = ko.utils.unwrapObservable(modelValue);
if (elementValue === currentValue)
return;
if (ko.isObservable(modelValue)) {
modelValue(elementValue);
}
};
ko.utils.registerEventHandler(element, "click", updateHandler);
},
update: function (element, valueAccessor) {
var elementValue = ko.bindingHandlers.isChecked.getElementDeclaredValue(element);
element.checked = elementValue === ko.utils.unwrapObservable(valueAccessor());
}
};
The two Boolean methods ("parse" and "isBool") are defined as follows:
Boolean.isBool = function (value) {
return (/^(?:true|false)$/i).test(value);
};
Boolean.parse = function (value) {
return (/^true$/i).test(value);
};
I'll ignore any comments that say I shouldn't be modifying a built-in object prototype; I'll do as I damn well please ;-).
Usage is the same as the checked binding. The "value" attribute is optional, unless you want the checked state to represent false:
<input type="radio" id="rbNewClaim" name="ClaimType" value="false" data-bind="checked: isExistingClaim" />
Hope this helps someone.
I gave up trying to get this to work with the bool values and created an array of selected objects and handled it that way. It isn't the optimal solution, but I was tired of fighting this.

Resources