Mvc razor radio button get default value from model - html

I've an Hotel model and there is a HotelPrice list in the model.
What i'm trying to do is when user display hotel detail page let hotel prices' info be shown, also they can be editable. I've a breakfastIncluded property on HotelPrice instances which i have to display as radio button.
Here is my code:
<div>
#{
foreach(var hotelPrice in Model.HotelPrices)
{
<label class="mt-radio-inline>
#Html.RadioButtonFor(hotelModel => hotelPrice.breakfastIncluded, "1", new { #checked = (hotelPrice.Breakfast.ToString() == "1") })Yes
<span></span>
</label>
<label class="mt-radio-inline>
#Html.RadioButtonFor(hotelModel => hotelPrice.breakfastIncluded, "0", new { #checked = (hotelPrice.Breakfast.ToString() == "0") })No
<span></span>
</label>
}
}
When i display my page(i could not come editing part, yet), all breakfastIncluded properties' radio buttons are displayed as unassigned and the last one's radio button is displayed wrongly(i.e it has to be "Yes" but it seems like "No").
However, when i checked by Inspect tool of browser, all of the radio buttons' checked property appears correct(i.e if it should be "Yes" that radio button's checked is true and "No"'s checked is false).
I'm new to html and i could not figure out why that happens. Can you help me? Thanks in advance.

By applying solutions in comments. I used for instead of foreach and it appears that i shouldn't set checked value since the radio buttons have values.

Related

Is it possible to use [maxSelectedLabels] property in an ngif condition?

I'm using Prime NG Multiselect component and I want to show selectedItemsLabel="{0} Selected" when there are more than 3 selected checkboxes, but if all of the checkboxes are selected, then selectedItemsLabel="All" should be shown in the placeholder.
I'm new to angular and I been following documentation of this MultiSelect component, yet this doesn't show the options to able to implement multiple conditions of properties, and I was wondering if it's even possible.
Example of how It might be
<ng-template pTemplate="filter" let-value let-filter="filterCallback">
<p-multiSelect
[ngModel]="value"
[options]="routeOptions"
placeholder="Any"
(onChange)="filter($event.value)"
optionLabel="name"
selectedItemsLabel="{0} selected"
[maxSelectedLabels]="3"
>
<ng-template let-option pTemplate="item">
<div>
<span class="p-ml-1">{{ option.name }}</span>
</div>
<div *ngIf="[maxSelectedLabels="routeOptions.length - 1"] Then selectedItemsLabel="All"></div>
</ng-template>
</p-multiSelect>
</ng-template>
Yes, you can. First give the component a ref with # like this:
<p-multiSelect
#myMultiSelect
[ngModel]="value"
[options]="routeOptions"
placeholder="Any"
(onChange)="filter($event.value)"
optionLabel="name"
selectedItemsLabel="{0} selected"
[maxSelectedLabels]="3"
>
.......
Then you have access to it:
<div *ngIf="myMultiSelect.maxSelectedLabels === routeOptions.length - 1">Im visible</div>
If the option of maxSelectedLables is the length - 1 of routeOptions then the div is visible. That is how ngIf works
BUT
Thats not what you want. You wanna set the selectedItemsLabel property. And you have it not understand correctly. You set the maxSelectedLables to 3 as example AND set the selectedItemsLabel directly, too! The text of the selectedItemsLabel will be only shown if needed (controlled by the component).
<h5>Basic</h5>
<p-multiSelect #meins [options]="cities" [(ngModel)]="selectedCities" defaultLabel="Select a City" optionLabel="name"
[maxSelectedLabels]="3" selectedItemsLabel="{0} items selected">
</p-multiSelect>
Look here the Stackblitz!
The documentation of ng-prime will helps, too and say:
selectedItemsLabel: Label to display after exceeding max selected labels e.g. ({0} items selected), defaults "ellipsis" keyword to indicate a text-overflow.
UPDATE 18.02.2023
You wanna show "ALL" only if all items selected. So add the onChange event and bind the selectedItemsLabel. Why binding? It has some problems with a condition in it. So we make it inside the code.
HTML
<p-multiSelect [options]="cities" [(ngModel)]="selectedCities" defaultLabel="Select a City" optionLabel="name"
[maxSelectedLabels]="2" [selectedItemsLabel]="bindTest" (onChange)="onChange()">
</p-multiSelect>
Inside the code do the follow with onChange:
Code
onChange() {
if (this.selectedCities.length === this.cities.length) {
this.bindTest = "ALL";
this.changeRef.detectChanges();
}
else {
this.bindTest = "{0} items selected";
this.changeRef.detectChanges();
}
}
Now it works how you wish. One important thing: We use changeRef.detectChanges(); Without this the components selected text will not changing directly. Import it in the components constructor:
constructor(
private countryService: CountryService,
private primengConfig: PrimeNGConfig,
private changeRef: ChangeDetectorRef
) {
.....
I made a Stackblitz of the problem: https://stackblitz.com/edit/primeng-tablefilter-demo-ipt7y1?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts
(Expand the page to the left to view the column filter in the stackblitz)
If you notice, the clear button doesn't clear the selected textbox anymore. After some testing it seems the [(ngModel)] breaks it, I think it got to do something with two-way binding? It is not shown in the stackblitz, but if you include
(onChange)="filter($event.value)"
the clear button still clears the filter from the table, but not in the selected textbox.
I found out that there is this property
[showClear]="true"
That adds an X at the end of the textbox that clears it out. Sadly, the styling/positioning is not what I need.
What could be the ways to fix the clear button ? Add a ts function to clear out the selected values? If so, how to bind it to the clear button because it is generated from
<p-columnFilter
display="menu"
menu property and I had no luck to find the way to try add/change functionality to that button.

how to handle radio button in the same view for both create and edit

I want to display the radio button with default value while loading the view for Add. The same radio button should display the value tagged to the model property while loading for Edit. may be based on some value from the controller store in viewbag.
The code will show the checked radio button value while Edit. For Add function the same view should show default value. But it is showing none of the radio button selected.
<td>
#{
foreach (var item in (SelectList)ViewBag.FilterFieldOptions.BrandSelectList)
{
#Html.RadioButtonFor(model => model.GenericBrand, item.Value, Model.GenericBrand == item.Value ? new { #checked = "checked" } : null) #item.Text
}
}
</td>

How is a radio button unchecked, if there's only one button?

I have these two radio buttons inside an Input Form:
<input type="radio" name="info_only_on" value="yes"> Info-only
<input type="radio" name="info_only_on" value="off"> (Clear Button)
It creates two buttons, so the user can check info-only and then turn off info-only if they made a mistake. I created the 2nd button because once the radio button is checked, clicking it again, doesn't deselect it.
I've switched to type="checkbox", which does let the user deselect.
<input type="checkbox" name="info_only_on" value="yes">
Looking at specs for the radio type button, I'm not seeing anything for the user unchecking it. What am I missing?
I'm using html, php and avoiding javascript.
The php used to check the box value is:
// When info_only_on is set to clear, it's value should be passed here as "no"
if($_POST["info_only_on"] == "yes")
{ $info_only = "Added Member info online but not paying online. "; }
else
{ $info_only = " "; }
// BUILD UP MESSAGE to email to our membership chair
$MsgToWrite = "\r\n" . $BasicInfo . $PhoneInfo . $EmailInfo;
If ($info_only <> " ")
{ $MsgToWrite = $MsgToWrite . "\r\n" . $info_only; }
I don't think that you can do it without javascript, here is a simple example :
HTML Code :
<input type="radio" name="name" id="radioBtn" onclick="test(this)" /> Radio
Javascript Code :
var radioState = false;
function test(element){
if(radioState == false) {
check();
radioState = true;
}else{
uncheck();
radioState = false;
}
}
function check() {
document.getElementById("radioBtn").checked = true;
}
function uncheck() {
document.getElementById("radioBtn").checked = false;
}
Take a look here : https://jsfiddle.net/eloufirhatim/ypwhugxz/
Unfortunately, there is no way to deselect a single radio button using HTML. In HTML, exactly one radio button needs to be selected. If you want the ability to deselect all radio buttons after one was selected, then you will have to use javascript for this.
From Wikipedia: "It is possible that initially none of the radio buttons in a group are selected. This unselected state cannot be restored by interacting with the radio button widget, though it may be possible through other user interface elements." https://en.wikipedia.org/wiki/Radio_button

Is there a way to set the For property of label otherwise than ID of an element?

I've this code for a view (ASP.NET MVC3), and I'm trying to add a for attribute on both the labels
#Html.RadioButtonFor(m => m.Sanctioned, true, new { #checked = "checked"})
<label For="">Yes</label>
#Html.RadioButtonFor(m => m.Sanctioned, false, new { })
<label For="">No</label>
I know it can be assigning an ID to both the radio buttons and refer them in For attribute of Labels respectively, but the situation here is, when I'm setting the IDs other than default, my Model is not getting posted back to controller. So, is there any way or work around to assign For attribute of Label control to point to the Radio buttons? Any suggestion or Feedback is highly appreciated.
This always works normal for me without "For" attribute and Label:
#Html.RadioButtonFor(m => m.Sanctioned, true, new { #checked = "checked"}) Yes
#Html.RadioButtonFor(m => m.Sanctioned, false) No
May be I don't understand your question currectly, but why you really need it?

checkbox and input field correlation in knockout

Description:
I have two things, a checkbox and input field. Here's what I want. In my viewmodel, I have two observables, one which saves the check box check/uncheck(ture or false), and another, which saves the input field value. Both of these values come from the database, but I have them as static here to simplify things. So, when the page loads and if the checkbox value is true, the input field should be enabled and it should display the value.The checkbox should also be displayed as checked. If the checkbox is then uncheked, the input field value should be zero and the input field should be disabled. If the checkbox is then checked after unchecking, the input field value should still be zero.
Fiddle:
data-bind="checked: boxChecked" type="checkbox" ></input>
<br/>
Result:
<input data-bind="enable: boxChecked() == true,
value: boxCheked() = true ? result : result = 0" type="text"></input>
http://jsfiddle.net/KGSUD/1/
I have been playing around with the fiddle for quite some time but couldnt figure it out.
I will appreciate your help folks.
I would take the logic out of the view (HTML) and put it in the ViewModel.
Html:
<input data-bind="checked: boxChecked" type="checkbox" ></input>
<br/>
Result:
<input data-bind="enable: boxChecked, value: result" type="text"></input>
JS:
var ViewModel = function() {
var self = this;
self.boxChecked = ko.observable(true);
self.result = ko.observable('10');
self.boxChecked.subscribe(function(newValue) {
if (!newValue)
self.result("0");
});
};
The subscription will take of setting the result, the html bindings become simpler. Here is the fiddle