ASP.NET MVC - Multiple Radio Buttons selections being allowed, why? - asp.net-mvc

Question Background:
I have two groups of Radio buttons in a menu. One group features 2 Radio buttons that allow a user to select a group of items to being sorted and displayed by their price either from 'High To Low' or 'Low To High'.
The second group of Radio buttons allows users to search for results from 3 different online marketplaces.
The Issue:
Currently the first group of Radio buttons (the price sort group) is working fine, if I click 'High To Low' then that Radio buttons will be selected, if I then select 'Low To High' this will be selected.
The second group with the 3 radio buttons for the marketplaces is causing me issues. This is allowing all three radio buttons to be checked instead of just one, and once all checked the user cannot unchecked them, as shown:
The Code:
this is the MarkUp in my View. I am using RadioButtonsFor Razer controls binding each Radio button to a specific property from the ViewModel.
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButtonFor(model => model.amazonAndEbay, true, new { id = "amazonEbayBox", #checked = "true" })<img class="originPic" src="#Url.Content("~/Images/amazon.png")" /> <img class="originPic" src="#Url.Content("~/Images/ebay.png")" /> Amazon & Ebay</label>
</div>
</div>
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButtonFor(model => model.amazonOnly, true, new { id = "amazonCheckBox" })<img class="originPic" src="#Url.Content("~/Images/amazon.png")" /> Amazon Only</label>
</div>
</div>
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButtonFor(model => model.ebayOnly, true, new { id = "ebayCheckBox" })<img class="originPic" src="#Url.Content("~/Images/ebay.png")" /> Ebay Only</label>
</div>
</div>
The HomePageVM:
public class HomePageVM
{
public bool highToLow { set; get; }
public bool lowToHigh { set; get; }
public bool amazonAndEbay { set; get; }
public bool amazonOnly { set; get; }
public bool ebayOnly { set; get; }
}
The Radio Buttons as rendered in Chrome:
<div class="form-group">
<div class=" maxPricePad">
<label>
<input checked="true" data-val="true" data-val-required="The amazonAndEbay field is required." id="amazonEbayBox" name="amazonAndEbay" type="radio" value="True"><img class="originPic" src="/Images/amazon.png"> <img class="originPic" src="/Images/ebay.png"> Amazon & Ebay</label>
</div>
</div>
<div class="form-group">
<div class=" maxPricePad">
<label>
<input data-val="true" data-val-required="The amazonOnly field is required." id="amazonCheckBox" name="amazonOnly" type="radio" value="True"><img class="originPic" src="/Images/amazon.png"> Amazon Only</label>
</div>
</div>
<div class="form-group">
<div class=" maxPricePad">
<label>
<input data-val="true" data-val-required="The ebayOnly field is required." id="ebayCheckBox" name="ebayOnly" type="radio" value="True"><img class="originPic" src="/Images/ebay.png"> Ebay Only</label>
</div>
</div>
Any help determing why I am getting all 3 checkboxes to select would be much appreciated.

Very sill lapse in concentration and just realized I'm using different models values for each property instead of one common one.

If you want only one selection from the group of radio buttons then you have to give them a common name, which will group them together and allow you to select only one from the group. The example lets you choose either Camaro or Mustang, but not both of them, since they have the same name, which means that they belong to the same group of items:
<input type="radio" name="car"/> Camaro <br/>
<input type="radio" name="car"/> Mustang <br/>
This example will let you choose one car (Camaro or Mustang) and one color (Yellow or Green):
<input type="radio" name="car"/> Camaro <br/>
<input type="radio" name="car"/> Mustang <br/>
<input type="radio" name="color"/> Yellow<br/>
<input type="radio" name="color"/> Green<br/>

The reason you are getting all three checkboxes selected in the Marketplaces group is that you're using separate names for each radio button in this button group. All buttons that ought to be mutually exclusive should be part of one group represented by one label. Also, since you're declaring each radio button separately and individually, I think there's no need to use HtmlRadioButtonFor. Simply try the following changes to your code. Note that I named your radio button group as, "Marketplaces":
The Code:
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButton("Marketplaces", model.amazonAndEbay, new { id = "amazonEbayBox", #checked = "true" })<img class="originPic" src="#Url.Content("~/Images/amazon.png")" /> <img class="originPic" src="#Url.Content("~/Images/ebay.png")" /> Amazon & Ebay</label>
</div>
</div>
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButton("Marketplaces", model.amazonOnly, new { id = "amazonCheckBox" })<img class="originPic" src="#Url.Content("~/Images/amazon.png")" /> Amazon Only</label>
</div>
</div>
<div class="form-group">
<div class="maxPricePad">
<label>#Html.RadioButton("Marketplaces", model.ebayOnly, new { id = "ebayCheckBox" })<img class="originPic" src="#Url.Content("~/Images/ebay.png")" /> Ebay Only</label>
</div>
</div>

Related

ASP.NET MVC hidden field still getting name and passing to controller

I have this control that is hidden and the user need to check the input control for it to be show. I am getting the model fill with data and I wanted to see how I can only get data in the controller if it is selected ?
View
<input type="checkbox" value="91" name="chkProduct">
<label>Other</label>
<input type="hidden">
<input type="hidden" asp-for="Other">
<div id="sourceSection_91" style="">
<div class="row" id="ddRow_6" data-source="sourceSection_91">
<div class="col-md-11 !important">
<div class="form-group">
<label class="control-label source-label">Other</label>
<input class="form-control" id="enteredOtherSource" name="enteredOtherSource[0].Other" type="text" value="">
<span class="field-validation-valid text-danger" data-valmsg-for="enteredOtherSource[0].Other" data-valmsg-replace="true"></span>
<input value="91" data-val="true" data-val-number="The field SourceId must be a number." data-val-required="The SourceId field is required." id="SourceId" name="enteredOtherSource[0].SourceId" type="hidden">
</div>
</div>
<div class="col-md-1 deleteBtn">
</div>
</div>
Model
public class OtherSourceModel
{
public int SourceId { get; set; }
public string Other { get; set; }
}
Controller
foreach (var ordermaterial in model.enteredOtherSource)
{
ProjectMaterialUse _SelectedOtherProjectMaterial = new ProjectMaterialUse();
_SelectedOtherProjectMaterial.Source = new Values();
_SelectedOtherProjectMaterial.Source.Value = ordermaterial.SourceId;
_SelectedOtherProjectMaterial.Other = ordermaterial.Other;
_SelectedOtherProjectMaterial.IntendedUse = new Values();
_SelectedOtherProjectMaterial.IntendedUse = model.selectedIntendedUseId;
_permissionrequestWeb.SelectedProjectMaterial.Add(_SelectedOtherProjectMaterial);
}

Getting all the values (checked and unchecked) from the dynamic checkbox in mvc

I'm adding a textbox and a corresponding checkbox to the view on click of a button. These checkbox will determine if the textbox value needs to be shown or hidden.
With the below code I've getting all the textbox fields, but for the checkbox I only get the checked values.
This is the view part
$('#btn-Add-Key-Name').click(function (e) {
i++;
e.preventDefault();
$(`<div class="row" id="rowid`+ i +`">
<div class= "col col-4" >
<section>
<label class="input">
<i class="icon-prepend fa fa-id-badge"></i>
<input type="text" name="KeyName" value="" placeholder="Key Name">
</label>
</section>
</div>
<div class="col col-2">
<label class="checkbox">
<input type="checkbox" name="IsKeyValid" value="true">
<i></i> Key
</label>
</div>
</div >`).appendTo($fields);
});
On the Controller
public JsonResult AddKeyToDB(string[] KeyName, IEnumerable<string> IsKeyValid)
{
}
//Is there a way to get the unchecked values as well for eg:
keyName = ["private", "public"] ,
IsKeyValid = ["false", "true"]
In your html you dont need to hard-code value of checkbox thats why you are only having checked values. So you need to make following change to your code. Just remove value="true" from input type checkbox.
<input type="checkbox" name="IsKeyValid" >

How to show password entered when checkbox is clicked?

in my form i have one checkbox so when i check the checkbox it should show password entered in password field.i am doing it using angular 7.
<div class="form-group">
<label for="Password" class="control-label">Password</label>
<div>
<input type="password" class="form-control" name="Password" ngModel
#pwd="ngModel" placeholder="Password" required pattern="^(?=.*[a-z])(?
=.*
[A-Z])(?=.*\d)(?=.*[#$!%*?&])[A-Za-z\d#$!%*?&]{8,}$">
<div *ngIf= pwd.invalid>
<small class="form-text text-danger" *ngIf=
pwd.errors.required>Password Required</small>
<small class="form-text text-danger"
*ngIf=pwd.errors.pattern>Minimum eight characters, at least one
uppercase letter, one lowercase letter, one number and one special
character.</small>
</div>
</div>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input"
[disabled]="pwd.invalid">
<label class="form-check-label" id="show" for="exampleCheck1">Show
Password</label>
</div>
By checking the checkbox it should show password entered in the password field.
Hi and welcome on Stackoverflow!
Try to switch between type="password" and type="text" based on checkbox value.
Add #showPassword to your checkbox input, like that :
<input #showPassword type="checkbox" class="form-check-input" [disabled]="pwd.invalid">
Then on your password field :
<input type="showPassword.checked ? 'text' : 'password'" .... />
EDIT (in case you did not solve it yet, and for others) :
component.ts
// show/hide boolean variable
showPassword: boolean;
constructor() {
// init value in constructor
this.showPassword = false;
}
// click event, show/hide based on checkbox value
showHidePassword(e) {
this.showPassword = e.target.checked;
}
component.html
<input [type]="showPassword ? 'text' : 'password'" />
<input type="checkbox" (change)="showHidePassword($event)" > toggle view

Input validation generating data-* attributes ONLY on Primary key and checkbox type input tags

I've created a sample ASP.NET MVC Core 1.1 web app created using VS2015-Update3. It generates input tags with data -* attributes only on a model property that is a Primary Key, and on a property that is of type bool. For instance, in the following example the generated html (shown below) is showing the data-attributes only on the input tag generated for properties MyEntityId and Prop2 of the model. NOTE: I'm using the default ASP.NET Core Web Application template that automatically installs Jquery, Bootstrap, etc.
Model:
public class MyEntity
{
public int MyEntityId { get; set; }
public string Prop1 { get; set; }
[Column(TypeName = "char(2)")]
[RegularExpression(#"^[0-9]{2,2}$", ErrorMessage = "Must enter two digit numbers"), StringLength(2)]
public string TestCode { get; set; }
public DateTime? StartDate { get; set; }
public bool Prop2 { get; set; }
}
View
<form asp-controller="TestController" asp-action="TestAction" method="post" class="form-horizontal">
<div asp-validation-summary="All" class="text-danger"></div>
<div><input type="hidden" asp-for="MyEntityId" /></div>
<div class="form-group">
<label asp-for="Prop1" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Prop1" class="form-control" style="margin-top:15px;" />
<span asp-validation-for="Prop1" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="TestCode" class="col-md-2 control-label"></label>
<div class="col-md-2">
<input asp-for="TestCode" class="form-control" />
<span asp-validation-for="TestCode" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="StartDate" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="StartDate" type="date" class="form-control" />
<span asp-validation-for="StartDate" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Prop2" class="col-md-2 control-label"></label>
<div class="col-md-1">
<input asp-for="Prop2" class="form-control" style="zoom:0.5;margin-top:25px;" />
<span asp-validation-for="Prop2" class="text-danger"></span>
</div>
</div>
<button type="submit" name="submit" value="testVal">Save</button>
</form>
Generated Html:
<div><input type="hidden" data-val="true" data-val-required="The MyEntityId field is required." id="MyEntityId" name="MyEntityId" value="54321"></div>
<div class="form-group">
<label class="col-md-2 control-label" for="StateName">Prop1</label>
<div class="col-md-2">
<input class="form-control" readonly="" type="text" id="Prop1" name="Prop1" value="TestVal">
<span class="text-danger field-validation-valid" data-valmsg-for="Prop1" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="TestCode">TestCode</label>
<div class="col-md-2">
<input class="form-control" type="text" id="TestCode" name="TestCode" value="">
<span class="text-danger field-validation-valid" data-valmsg-for="TestCode" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="StartDate">Start Date</label>
<div class="col-md-10">
<input type="date" class="form-control" id="StartDate" name="StartDate" value="2015-10-01">
<span class="text-danger field-validation-valid" data-valmsg-for="StartDate" data-valmsg-replace="true"></span>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="Prop2">Test Prop2</label>
<div class="col-md-1">
<input class="form-control" data-val="true" data-val-required="Test Prop2 is required." id="Prop2" name="Prop2" style="zoom:0.5;margin-top:25px;" type="checkbox" value="true">
<span class="text-danger field-validation-valid" data-valmsg-for="Prop2" data-valmsg-replace="true"></span>
</div>
</div>
I'm assuming your issue is that TestCode does not have validation on it, despite having both RegularExpression and StringLength attributes applied. MyEntityId and Prop2 are non-nullable, so there's an implicit required validation for those, while Prop1 and StartDate are nullable and do not have any explicit validation applied. As a result, those are rightly not validated.
TestCode is weird, though. I'm not sure you'd actually get data-* attributes, as both the regular expression and string length can be satisfied using the HTML attributes pattern and maxlength, respectively. But, you should then have pattern and maxlength applied to the input for TestCode which is not the case.
According to the docs, the code you have should work, and at the least, it seems that StringLength is applied via data-val-maxlength rather than (or perhaps in addition to) using the maxlength attribute. There's either some bug at play, or there's something else in your codebase that is preventing the correct behavior from occurring. However, without more code, it's impossible to say.

MVC 5, Using Checkbox for same model property twice in a page but inside different forms

Model property which I intend to use inside two forms
public class TestModel
{
[Display(Name = "Terms Accepted")]
[Range(typeof(bool), "true", "true", ErrorMessage = "You need to accept terms and conditions to proceed!")]
public bool TermsAccepted { get; set; }
}
view Page
<form id="form1">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted, new { #id = "chk1" })
</div>
<div class="col-md-3">
<input type="submit" id="button1" onclick="return isFormValid('form1');" value="Submit Form 1"/>
</div>
</div>
</form>
<form id="form2">
<div class="row">
<div class="col-md-3">
#Html.CheckBoxFor(m => m.TermsAccepted, new { #id = "chk2" }) I accept terms and conditions
#Html.ValidationMessageFor(m => m.TermsAccepted)
</div>
<div class="col-md-3">
<input type="submit" id="button2" onclick="return isFormValid('form2');" value="Submit Form 2"/>
</div>
</div>
</form>
When this UI is rendered on the page, checkbox inside the 1st form do contains attributes for RangeDataAnnotation while checkbox inside 2nd form doesn't have any attributes for data annotation. So this results into 2nd form doesn't throw any validation on submission.
Html of checkboxes which get rendered on UI
Inside form 1:
<input name="TermsAccepted" class="input-validation-error" id="chk1" aria-describedby="TermsAccepted-error" type="checkbox" value="true" data-val="true" data-val-range-min="True" data-val-range-max="True" data-val-range="You need to accept terms and conditions to proceed!">
Inside form 2:
<input name="TermsAccepted" id="chk2" type="checkbox" value="true">
Any suggestions to make this work in both forms?

Resources