Getting all the values (checked and unchecked) from the dynamic checkbox in mvc - asp.net-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" >

Related

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

mvc radiobuttonfor in editortemplate keyboard navigation does not set model

Context:
Model generating some RadioButtonFor groupings as input to answer questions.
What is happening:
Case 1. When mouse click on a radio option the display looks correct. When the [HttpPost] ActionResult(model) for the page is triggered the Model.Answer comes through with the correct value. Which is good and desired.
Case 2. When navigating with the keyboard to the radio group and selecting one with arrow keys the display looks correct. But when the [HttpPost] ActionResult (model) is triggered the Model.Answer value is unchanged from what it was loaded as on page load.
Here is the code that makes the radio group:
#model NexusPWI.ViewModels.Wizard.QuestionModel
#* Dynamically generate and model bind controls for QuestionModel *#
#{
<div class="row d-contents">
<div class="form-group">
<div class="question">
<div class="col-lg-2 d-contents">
<div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons">
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.Yes ? "active" : "")" for="#Model.Answer">
#YesNoNAOptions.Yes.ToString().ToUpper()
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.Yes, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.No ? "active" : "")" for="#Model.Answer">
#YesNoNAOptions.No.ToString().ToUpper()
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.No, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
#if (!Model.NaInvalid)
{
<label class="btn QuestionRadio btn-default #(Model.Answer == YesNoNAOptions.NA ? "active" : "")" for="#Model.Answer">
N/A
#Html.RadioButtonFor(Model => Model.Answer, YesNoNAOptions.NA, new { #onfocus = "radiofocus(event)", #onblur = "radioblur(event)" })
</label>
}
</div>
</div>
<div class="col-lg-9 d-contents">
<div class="row">
<p>
<strong>#Model.Question</strong>
</p>
</div>
#Html.HiddenFor(x => Model.Question_IdentityMarker, new { #class = "Question_IdentityMarker" })
</div>
</div>
</div>
</div>
}
Here is an example of the html that is generated:
<div class="form-group">
<div class="question">
<div class="col-lg-2 d-contents">
<div class="btn-group btn-toggle group-sm d-contents" data-toggle="buttons">
<label class="btn QuestionRadio btn-default " for="No">
YES
<input data-val="true" data-val-required="The Answer field is required." id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="Yes" type="radio">
</label>
<label class="btn QuestionRadio btn-default active" for="No">
NO
<input checked="checked" id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="No" type="radio">
</label>
<label class="btn QuestionRadio btn-default " for="No">
N/A
<input id="Questions_0__Answer" name="Questions[0].Answer" onblur="radioblur(event)" onfocus="radiofocus(event)" value="NA" type="radio">
</label>
</div>
</div>
<div class="col-lg-9 d-contents">
<div class="row">
<p>
<strong>Do you charge sales tax?</strong>
</p>
</div>
<input class="Question_IdentityMarker" id="Questions_0__Question_IdentityMarker" name="Questions[0].Question_IdentityMarker" value="CUSTOMERSALESTAX" type="hidden">
</div>
</div>
</div>
EDIT Adding onFocus & onBlur at request:
onFocus & onBlur are css highlighting for the keyboard navigation to make it more clear for the user where they are in the page.
function radiofocus(event) {
// Get event object if using Internet Explorer
var e = event || window.event;
// Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
if (e.target) {
var addClass = focusClass(e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
} else {
var addClass = focusClass(e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className, "r");
e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = addClass;
}
};
function radioblur(event) {
// Get event object if using Internet Explorer
var e = event || window.event;
var removeClass = focusClass("", "r").trim();
// Check the object for W3C DOM event object, if not use IE event object to update the class of the parent element
if (e.target) {
e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.target.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
} else {
e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className = e.srcElement.parentNode.parentNode.parentNode.parentNode.parentNode.className.replace(removeClass, "");
}
};
Why do the keyboard navigated changes not get back to the controller?
Anything to add to make this clearer?
Side note: For some reason before a value is chosen in the radio group the keyboard tab navigation is stopping for each radio answer for a question.

Show or Hide History in MVC

I am working on a registration form. I want to show and hide my users past registrations using a button.The button should only show or hide registrations that are gone not the upcoming ones This is what I have so far. Pleasssseeee Help.
<div class="Table01">
<button id="older">Show Registration History</button>
#foreach (var sm in Model)
{
var tmp = #sm.SeminarNm.Replace("&", "and");
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 well table-item" align="left" data-toggle="tooltip" data-eventtype="#tmp" data-placement="top" title="#tmp">
<span class="sortName mid-weight"> #sm.SeminarNm</span>
<span class="sortDate alert-info">(ON #string.Format("{0:yyyy-MM-dd}", #sm.SessionStartDT) IN #sm.SessionCityNm)</span>
<div class="row " style="margin-top:10px">
#if (#sm.IsEditable == "Y")
{
using (Html.BeginForm("EditRegister", "App", FormMethod.Post, new { onclick = "showPageLoadingSpinner()" }))
{ #Html.AntiForgeryToken()
<div class="col-xs-12 col-md-6 col-lg-6">
<input class="btn btn-success " name="submitButton" type="submit" value="Edit" />
<input type="hidden" value="#sm.RegistrantSeq" name="hiddenseq" />
<input type="hidden" value="0" name="cntView" />
<input type="hidden" value="EditRegister" name="cntStage" />
</div>
}
}
#using (Html.BeginForm("ViewRegister", "App", FormMethod.Post))
{ #Html.AntiForgeryToken()
<div class="col-xs-12 col-md-6 col-lg-6 col">
<input class="btn btn-info" name="submitButton" type="submit" value="View" />
<input type="hidden" value="#sm.RegistrantSeq" name="hiddenseq" />
<input type="hidden" value="ViewRegister" name="cntStage" />
</div>
}
//
</div>
}
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script>
var $btns = $('.btn').click(function () {
if (this.id == 'older') {
$('#child > div').toggle(450);
}
$btns.removeClass('active');
$(this).addClass('active');
})
</script>
My Program Pic
I dont know if I need some sorting javascript function to display only those sessions that are in the past. Nothing seems to be working.
Assuming old registrations are any item with SessionStartDT value earlier than current date, you can set an html data attribute on each item's container div indicating whether it is an old item or new item and when user clicks the hide/show button, toggle the visibility of these items.
#foreach (var sm in Model)
{
<div data-old="#(p.SessionStartDT.Date < DateTime.Today.Date)">
<!-- your existing code for rendering each item goes here -->
</div>
}
And in the javascript part, when the button is clicked, make select the elements who's data-old attribute value is True (which we set via our C# expression which results in a boolean value) and toggle the visibility.
$(document).ready(function() {
$("#older").click(function(e) {
e.preventDefault();
$("[data-old='True']").toggle();
});
});

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?

How can I show a validation div when data-validation triggers

Instead of styling the data-valmsg-summary produced by Html.ValidationSummary() in a custom way, I would like to just show the box with the twitter bootstrap style applied to it whenever the field validation fails. How would I go about doing this? Currently my markup looks like this:
..
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<div class="container">
<div class="row-fluid">
<br />
<br />
<br />
<br />
</div>
<div class="row-fluid">
<form class="navbar-form pull-right" action="/Login?ReturnUrl=%2F" method="post">
<h3 class="modal-header">Please sign in</h3>
<input data-val="true" data-val-required="The Username field is required." id="Username" name="Username" type="text" class="input-large" placeholder="Username">
<input data-val="true" data-val-required="The Password field is required." id="Password" name="Password" type="password" class="input-large" placeholder="Password">
<label class="checkbox">
<input type="checkbox" value="remember-me">
Remember me
</label>
<button type="submit" class="btn btn-danger">Sign in</button>
<br />
<br/>
<div data-valmsg-summary="true" class="alert alert-danger alert-block" id="formval" >
<span class="close pull-right" data-dismiss="alert">×</span>
<strong>Ooops!</strong> You seem to be missing something:
<ul>
<li style="display: none"></li>
</ul>
</div>
</form>
</div>
</div>
I've tried adding the style="display: none" to my div, but that does not seem to do the trick either.
I was looking for something else and stumbled on this. Thought I would post the answer for the next person since I am 5 months late. Add to your document ready.
//I dont want to validate my ajax forms take that if statement out if you want 2.
if ($('form:not([data-ajax="true"])').length != 0) {
var settings = $.data($('form:not([data-ajax="true"])')[0], 'validator').settings;
settings.submitHandler = function (form) {
//success
form.submit();
};
}
$("form").bind("invalid-form.validate", function (form, validator) {
var errors = validator.numberOfInvalids();
var message = "<ul>";
//loop thru the errors
for (var x = 0; x < validator.errorList.length; x++) {
var $group = $(validator.errorList[x].element).parent().parent(); //gets bootstrap class of form-group
var $element = $(validator.errorList[x].element); // gets the element to validate
var elementMessage = validator.errorList[x].message; // gets the message
$group.addClass("has-error"); // adds the bootstrap class has-error to the group
$element.popover({ content: elementMessage, placement: "right" }).popover("show"); // adds a popover
message += "<li>" + elementMessage + "</li>"; //appends message to list
}
message += "</ul>";
// Function I have to add alert to the page, but basically you can do whatever you want with the message now.
RegisterError("There was some errors with your submission!", message, false);
});

Resources