Is it possible assign the checked state to the value of the current checkbox in razor form without onclick method? - javascript

I have an ASP.Net Core MVC Web Application project.
I want to send the checkbox's checked state as the value to the model's related parameter on form submit.
I have seen so many examples that using jquery to get/set the value of the checkbox via onchange methods.
What I wonder is that is it possible to assign the current checkbox's checked state to the value in a similar way to the code below.(it doesn't work)
<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="#Model.IsActive" value="(this.checked)"
One of the simplest working examples I found is the following but it returns false if the checkbox is checked by default and its state is not changed.
<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="#Model.IsActive" onchange="if(this.checked) this.value='true'; else this.value='false';" >
I know that there are many ways to achieve what I want but I want the cleanest solution.
Thanks in advance!
Edit: The structure of my code is as follows:
View
#model MyModel
<form id="UpdateForm" class="was-validated" method="post" enctype="multipart/form-data" asp-controller="ControllerName" asp-action="Update">
<div class="modal-body">
<div class="form-group">
<input type="text" class="form-control" id="Name" name="DTO.Name" value="#Model.Name" required>
<input type="checkbox" id="IsActive" name="DTO.IsActive" checked="#Model.IsActive">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" data-save="modal">Update</button>
</div>
</form>
Controller
public async Task<IActionResult> Update(Guid id, UpdateDto DTO)
{
...
}
Solution
https://www.learnrazorpages.com/razor-pages/forms/checkboxes
In View
<input type="checkbox" " id="IsActive" name="DTO.IsActive" checked="#Model.IsActive" value="true">
In DTO Object Set Default
public bool IsActive { get; set; } = false;

Yes you can do it by using an inline razor statement #()
It would look something like this:
<input type="checkbox" id="IsActive" name="DTO.IsActive" #(Model.IsActive ? "checked" : "") />
also you could use the Checkbox helper
#Html.CheckBoxFor(model => model.IsActive )

Related

How to disable a Dynamic forms in Angular2

I have created a dynamic form based on data[fields] from JSON, but I need the form to be initially disabled, so that when we click on Edit then only form becomes editable.
Here is my code for form:
<div class="col-md-8 " [ngSwitch]="fieldInfo.dataTypeName">
<input *ngSwitchCase="'Text'"
class="form-control"
[(ngModel)]="pageInfoBeans.nameValueMap[fieldInfo.name]"
name="{{fieldInfo.name}}"
[required]="fieldInfo.preRequiredInd"
[maxLength]="fieldInfo.fieldSize">
<input *ngSwitchCase="'Email Address'"
type="email"
class="form-control"
[(ngModel)]="pageInfoBeans.nameValueMap[fieldInfo.name]"
name="{{fieldInfo.name}}"
[required]="fieldInfo.preRequiredInd"
[maxLength]="fieldInfo.fieldSize">
and in my component HTML which populates from above switch case :
<app-form class="" [fieldInfo]="fieldItem.fieldInfo" [pageInfoBeans]="pageInfoBeans"></app-form>
Initially set the form to disabled.
component.ts
showForm?:boolean = false;
component.html
<button (click)="showForm = !showForm">Edit</button>
<form *ngIf="showForm">
...form markup
</form>
You need to do something like this:
<button class='form-control' (click)='isEditable = !isEditable'>Edit Mode</button>
<div class="col-md-8 " *ngIf='isEditable' [ngSwitch]="fieldInfo.dataTypeName">
<input *ngSwitchCase="'Text'"
class="form-control"
[(ngModel)]="pageInfoBeans.nameValueMap[fieldInfo.name]"
name="{{fieldInfo.name}}"
[required]="fieldInfo.preRequiredInd"
[maxLength]="fieldInfo.fieldSize" />
<input *ngSwitchCase="'Email Address'"
type="email"
class="form-control"
[(ngModel)]="pageInfoBeans.nameValueMap[fieldInfo.name]"
name="{{fieldInfo.name}}"
[required]="fieldInfo.preRequiredInd"
[maxLength]="fieldInfo.fieldSize" />
</div>
[disabled]="!isEditable" where initialize isEditable = 'disabled' this could be added in both the text and email input fields.
Also in your edit button you can add a callback for click where you can set isEditable = ''.
#Directive({
selector : ["canbedisabled"]
})
export class Canbedisabled{
constructor(private el: ElementRef) {
}
#Input()
set blocked(blocked : boolean){
this.el.nativeElement.disabled = blocked;
}
}
<input formControlName="first" canbedisabled [blocked]="isDisabled">
You can solve it with a Directive. A directive named Canbedisabled and a property "blocked", for example. Write a setter for blocked and set it to nativelement.disabled property.
refer: https://github.com/angular/angular/issues/11271

Angular 4 - using ngModel inside (click)

So I have the following html:
<div class="workflow-row">
<input type="checkbox" id="new-workflow" [(ngModel)]="new_checkbox">
<label>New Workflow</label>
<input type="text" *ngIf="new_checkbox" placeholder="Enter Workflow Name">
</div>
<div class="workflow-row">
<input type="checkbox" id="edit-workflow" [(ngModel)]="edit_checkbox">
<label>Edit Workflow</label>
<select *ngIf="edit_checkbox"></select>
</div>
I want the checkboxes to act like radio buttons, ie: if one is checked, the other one becomes unchecked with angular 4. I tried doing
<input type="checkbox" id="edit-workflow" (click)="new_checkbox.checked = false"
[(ngModel)]="edit_checkbox">
but I get an error and it says that new_checkbox is undefined. The weird thing is that new_checkbox and edit_checkbox work inside the ngIf statements but not inside the (click)'s. What am I doing wrong?
I suggest you to try the following:
component.ts:
export class AppComponent {
edit_checkbox = false;
new_checkbox = true;
dropNewValue() {
this.new_checkbox = false;
}
dropEditValue() {
this.edit_checkbox = false;
}
}
Then in your template file, e.g. component.html, change your template slightly to:
<div class="workflow-row">
<input type="checkbox" id="new-workflow" [(ngModel)]="new_checkbox" (ngModelChange)="dropEditValue()">
<label>New Workflow</label>
<input type="text" *ngIf="new_checkbox" placeholder="Enter Workflow Name">
</div>
<div class="workflow-row">
<input type="checkbox" id="edit-workflow" [(ngModel)]="edit_checkbox" (ngModelChange)="dropNewValue()">
<label>Edit Workflow</label>
<select *ngIf="edit_checkbox"></select>
</div>
I've just tried this and it works. However I do recommend to switch to radio buttons approach, because you will get the same behavior out of the box.
Don't write Angular like you're writing regular javascript instead of
(click)="new_checkbox.checked = false"
do something like
// .html
(click)="uncheckNewCheckbox()"
// .js or .ts
uncheckNewCheckbox() {
this.new_checkbox.checked = false;
}

Two text html text inputs in two different places on the page with the same submit id

So I have a page called Index.cshtml
I have this input in a form with the id "cvr":
#using (Html.BeginForm("SendMailAsACompany", "Contract", null, FormMethod.Post, new { id = "cvr" }))
{
<input type="hidden" value=#Html.ViewData.Model.StudentId name="studentId" />
<input type="hidden" value=#Html.ViewData.Model.CompanyId name="companyId" />
<input type="hidden" value=#Html.ViewData.Model.ApplicationId name="applicationId"/>
if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
<input type="text" name="companyCVR" placeholder="Indsæt CVR-nr."/>
}
}
and at the bottom of the page I have the submit button with the id above ("cvr") where I am trying to add two more forms to pass on to the controller (repFirstName and repLastName):
#if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
using (Html.BeginForm("SendMailAsACompany", "Contract", null, FormMethod.Post, new { id = "cvr" }))
{
<input type="text" name="repFirstName" placeholder="Indsæt fornavn" />
<input type="text" name="repLastName" placeholder="Indsæt lastnavn" />
}
<input type="button" value="Submit" onclick="$('#cvr').submit();" class="btn btn-success" />
}
However they will not pass on submit, only the first value (the CPR above). However if I have all three values at the start, they will pass successfully.
How can I have the input in both places and still be able to submit and pass the data to the controller? Do I need two separate forms/ids ?
Only one form is required, remove the second form declaration and associate element with form using form attribute which is defined at the bottom of page.
The form attribute is used to associate an input, select, or textarea element with a form (known as its form owner).
#if (User.Identity.GetUserId() == Html.ViewData.Model.CompanyId)
{
<input type="text" name="repFirstName" placeholder="Indsæt fornavn" form="cvr"/>
<input type="text" name="repLastName" placeholder="Indsæt lastnavn" form="cvr"/>
<button form="cvr" class="btn btn-success">Submit</button>
}
If your generated HTML results in multiple elements that have the same ID, and then you have some inline javascript like this:
<input type="button" value="Submit" onclick="$('#cvr').submit();" />
Then the above javascript will work only for the first #cvr
That is one example of why you cannot / must not have multiple elements on the page with the same ID.
You must refactor your code to only use one element with any given ID. If need to have multiple elements with same moniker, use a class - so your javascript would become:
<input type="button" value="Submit" onclick="$('.cvr').submit();" />
and your generated HTML would be class="cvr" instead of id="cvr"
Alternately, you could ensure that each of your forms uses a different ID, such as id="cvr1", id="cvr2", id="cvr3" and then your javascript could be:
<input type="button" value="Submit" onclick="$('#cvr1, #cvr2, #cvr3').submit();" />

How can I disable my checkbox from AngularJS input?

<div ng-repeat="x in spaceutilization">
<input type="checkbox" name="{{x.filenumber}}" id="{{x.id}}" class = "pdffiles" value="101SP{{x.initials}}.dwg" /><label for="{{x.id}}"><button type = "button" class = "btn btn-primary btn-sm hidden-sm hidden-xs"> PDF</button></label><br />
</div>
I need to be able to add something to this snippet that disables the input checkbox based on another AngularJS input such as {{x.status}}. I tried simply doing:
<input type="checkbox" name="{{x.filenumber}}" id="{{x.id}}" class = "pdffiles" value="101SP{{x.initials}}.dwg" {{x.status}} />
Where status:'disabled' but that gave an output of
{{x.status}}=""
within the input element...which I don't understand why at all. But it seemed like the simplest route.
You need to use ng-disabled="expression" directive, on basic of expression evaluation value it add disabled attribute to that element.Also for better attribute values evaluation you could use ng-attr directive
Markup
<input type="checkbox" ng-attr-name="{{x.filenumber}}" ng-attr-id="{{x.id}}" class ="pdffiles"
value="101SP{{x.initials}}.dwg" ng-disabled="x.status == 'disabled'"/>
If x.status does return a bool value then you could directly used ng-disabled="{{x.status}}"

Angular form checkbox default value

I've been trying to grab hold of the Angular forms applying best practices for form validations, that forced me to use the form name and have all of the models as children of it so that I can bind the formname.$valid and all the other stuff.
However I haven't been able to set predefined values to any of the form sub models as I have no access to them in the controller.
My biggest problem right now is how to check for falsy checkboxes because initially the checkbox is unchecked but there is no value, it only gets populated when clicked to change the value.
Here is my form code
<form name="addAppForm" ng-if="creatingApp == false">
<input type="text" placeholder="App Name" required autofocus ng-model="addAppForm.appName">
<input icheck id="ios" type="checkbox" ng-init="addAppForm.iOS = false" ng-model="addAppForm.iOS">
<label for="ios"><i class="icon-apple"></i> iOS {{addAppForm.iOS}}</label>
<input icheck id="android" type="checkbox" ng-init="addAppForm.android = false" ng-model="addAppForm.android">
<label for="android"><i class="icon-android"></i> Android {{addAppForm.android}}</label>
<button ng-disabled="addAppForm.$invalid && (addAppForm.iOS != true && addAppForm.android != true)" type="submit" ng-click="addNewApp(addAppForm.iOS, addAppForm.android, addAppForm.appName)" class="button front-primary large radius expand">Let's GO!</button>
</form>
The "required" directive doesn't apply to the checkboxes and I've tried initializing the model but with no luck.
When you add a named form like that, it is added to your controller's scope. You can access it inside the controller using the name, similar to in the HTML:
$scope.addAppForm.android;
This should evaluate to true/false any time after the form has been set up, even if it hasn't been clicked yet.
Edit: Fiddle where form is accessed in the controller.
I've figured out what's wrong with my code, the ng-init actually works, I just mixed up the operators here -->> ng-disabled="addAppForm.$invalid && (addAppForm.iOS != true && addAppForm.android != true)"
Should have been ng-disabled="addAppForm.$invalid || (addAppForm.iOS != true && addAppForm.android != true)"
Still the problem persists of not being able to access the form from the controller not even in the same view outside of the form.
I still don't understand why u have to save your data in the Formcontroller u can use a object ( here i call it 'model' ) and put all your form values inside. Your Formcontroller object ( 'addAppForm' ) has functionality and saves validation errors see here : https://docs.angularjs.org/api/ng/type/form.FormController This object is added to the scope of your Controller late in the initialisation of your Controller
see: https://docs.angularjs.org/api/ng/directive/form
Directive that instantiates FormController.
If the name attribute is specified, the form controller is published onto the current scope under this name.
Here is the way to have the form invalid if not at least one checkbox is selected
var myApp = angular.module("myApp", []);
myApp.controller("myController1", function($scope) {
$scope.model = {
"ios": false,
"android": false
};
});
<div ng-app="myApp" ng-controller="myController1">
<form name="addAppForm">
<input type="text" placeholder="App Name" required autofocus ng-model="model.appName" />
<input id="ios" name="ios" type="checkbox" ng-model="model.ios" ng-required="!model.ios && !model.android" />
<label for="ios"><i class="icon-apple"></i> iOS</label>
<input id="android" name="android" type="checkbox" ng-model="model.android" ng-required="!model.ios && !model.android" />
<label for="android"><i class="icon-android"></i> Android</label>
<button ng-disabled="addAppForm.$invalid " type="submit" ng-click="addNewApp(model.ios, model.android, model.appName)" class="button front-primary large radius expand">Let's GO!</button>
</form>
</div>
<script src="https://code.angularjs.org/1.3.8/angular.min.js"></script>

Categories