Convert html to checkbox razor view - html

I have the following checkbox:
<input type="checkbox" id="seaMode" name="transportMode" value="Origin Service" />
<label for="seaMode" data-label="Sea">Sea</label>
However I am using razor view for that binding the view to the model:
#foreach (var val in Model.TransportList)
{
#Html.Label(val.Value, htmlAttributes: new { #for = label })
<i class=#val.Image></i>
#Html.CheckBox(label, false, new { value = #val.Text, name = "transportMode" })
}
Right now, it is returning it as below:
<label for="SEAMode">SEA</label>
<i class="icon-sea"></i>
<input id="SEAMode" name="SEAMode" type="checkbox" value="1">
<input name="SEAMode" type="hidden" value="false">
Any one good with html can please help me to add the correct class and attribute so as to render the html as the 1st one?
For info, val.Value has SEA and val.Text = 1 and so on.

If you're trying to add a class and data attributes then this should do it:
#Html.CheckBox(label, false, new { value = #val.Text, name = "transportMode", #class = "myCheckBox", data_label = "my data label value" })
Let me know if this helps.

Related

How to validate dynamic form in angular

Below is my code. According to the loop count, fName will increase. currently I am using ng-bootstrap-form-validation for validation. The issue if I validate using formControlName that's not working it's duplicating if one field(fName) is correct all the fields become correct.
Below is my HTML code,
<form [formGroup]="formGroup" (validSubmit)="onSubmit()">
<div class="results-traveler" *ngFor="let item of createLoopRange(selectedDataDetails[0].Adult); let ii= index;">
<div class="row">
<div class="col-12 heading" *ngIf="ii == 0 else travelCount">Traveller {{ii}}</div>
<div class="col-6 M-full-div">
<label>First Name</label>
<div class="inputContainer form-group">
<input class="InputField form-control" type="text" placeholder="Type Here" formControlName="fName" id="fName_{{i}}" />
</div>
</div>
</div>
</div>
<a class="SearchBtn" type="submit">CONTINUE</a>
</form>
Below is the typescript code I am using,
ngOnInit(): void {
this.bookingDetailsValidate();
}
bookingDetailsValidate() {
this.formGroup = new FormGroup({
fName: new FormControl('', [
Validators.required,
Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
])
});
}
onSubmit() {
console.log(this.formGroup);
}
Can anyone please guide me on how to do this. Thanks.
for fName use FormArray then add FormControl to FormArray and you can validate FormArray and every FormControl inside FormArray
example:
this.formGroup = new FormGroup({
fName: new FormArray([], [
Validators.required
])
});
...
const arrayOfNameControl = this.formGroup.get('fName') as FormArray
arrayOfNameControl.insert(0, new FormControl('',[
Validators.required,
Validators.pattern(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)
]));
You need form array here. Please refer the link.
Angular form array

How to create single page search form with ajax in MVC Razor

I'm a beginner in the ways of MVC / Razor... Basically I have 2 pages just for showing a search result from an API that I'm consuming with Json.
Index.cshtml: (Just a form)
#model ConsultaInterna.Models.SearchApi
<div class="jumbotron">
<h2>Consulta Interna</h2>
Placa
#using (Html.BeginForm("Search", "Home"))
{
<input asp-for="Model.Name" class="form-control" name="name" id="txtName" />
<input class="form-control" type="submit" id="ok" />
}
and Search.cshtml (Which also have the form. I want to leave just this page, right now I can't because if I load directly from Search.cshtml it gives me an error like
"Unexpected character encountered while parsing value: <. Path '', line 0, position 0. " (Obviously because I'm trying to load labels with a null search)
this is Search.cshtml
#model ConsultaInterna.Models.SearchApi
<div id="loader" class="spinner" style="display:none">OIE</div>
<div class="header formPesquisa">
#using (Ajax.BeginForm("Search", new AjaxOptions()
{
HttpMethod = "POST",
LoadingElementId = "loader",
UpdateTargetId = "resultado"
}))
{
<input placeholder="Placa" asp-for="Model.Name" name="name" id="txtName" width="30" />
<input class="pesquisa" type="submit" id="enviar" value="Ok" />
}
<div class="panel">Placa #Model.Name</div>
<div class="panel">Last Name / Model.LastName</div>
ALSO Important, the Ajax form isn't working properly... the loader won't show up.
You need to move your loader div into the Ajax.BeginForm.
You need also need to add the resultado div to display your result.
#using (Ajax.BeginForm("Search", "Home", new AjaxOptions()
{
HttpMethod = "POST",
LoadingElementId = "loader",
UpdateTargetId = "resultado"
}))
{
<div id="loader" class="spinner" style="display:none">OIE</div>
<input placeholder="Placa" asp-for="Model.Placa" class="pesquisa placa" maxlength="7" name="placa" id="txtPlaca" width="30" />
<input placeholder="CPF" asp-for="Model.CPF" class="pesquisa cpf" maxlength="11" name="cpf" id="txtCPF" />
<input class="pesquisa" type="submit" id="enviar" value="Enviar" />
<div id="resultado"></div>
}
<div class="panel">Placa #Model.Name</div>
<div class="panel">Last Name / Model.LastName</div>
</div>
You also need to make sure you have added the relevant reference to the specific unobtrusive ajax library. As an example:
BundleConfig
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive-ajax.min.js",
"~/Scripts/jquery.validate*"));
_layout.cshtml
#Scripts.Render("~/bundles/jqueryval")
Example controller action
[HttpPost]
public ActionResult Search(string placa, string cpf)
{
return new JsonResult { Data = "found", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

How to make Razor not display special characters as html

The page I'm working on displays content from a database in readonly input box. My problem is that it's displaying any special characters as the html code (ie: & displays as &). How do you get the code to display properly?
I'm using QuerySingle to connect to the database, don't know if that makes a difference. I'm new to using Razor. Any help is much appreciated.
Code in question:
var queryloan = "SELECT * FROM loans WHERE LoanId = #0";
var queryloandata = db.QuerySingle(queryloan, queryformstatus_submitted.doc_loanid);
<form class="jotform-form" action="submit-form.cshtml?isadmin=#(isadmin)&loanid=#(loanid)" method="post" name="form_30905105572145" id="30905105572145" accept-charset="utf-8">
<input type="hidden" name="formID" value="30905105572145" />
<input type="hidden" name="doc_id" value="#doc_id" />
<div class="form-all">
<ul class="form-section">
<li id="cid_3" class="form-input-wide">
<div class="form-header-group">
<h2 id="header_3" class="form-header">
Borrower Sources & Uses Summary
</h2>
#if (queryformstatus_submitted.doc_approval == "Pending Approval" || queryformstatus_submitted.doc_approval == "Approved")
{
<text><br />
<br />
<div class="error">
This form has already been submitted and cannot be edited. It is for reference only.</div></text>
}
#if(userid != queryformstatus_submitted.doc_userid){
<text><br/><br/><div class="error">You may not edit this form. It is for reference only.</div></text>
}
</div>
</li>
<li class="form-line" id="id_4">
<label class="form-label-left" id="label_4" for="input_4">
1. Property Name:
</label>
<div id="cid_4" class="form-input">
<input type="text" class=" form-textbox" id="input_4" name="q4_1Property" size="40" value="#Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName)"/>
</div>
</li>
I'm not sure but I believe it may be something in this helper function that's causing the html code:
#helper checkEmptyPreFill(IEnumerable<dynamic> queryinputvalue, string field_id, string defaultval, int cloned = 0) {
var reqValue = queryinputvalue.FirstOrDefault(r => r.field_name.Equals(field_id));
var return_value = "";
if(reqValue != null){
return_value = reqValue.field_data;
} else {
return_value = defaultval;
}
if(cloned == 1){
return_value = "";
}
#return_value
}
The razor helper returns a HelperResult object so you'll have to convert it to a string before you can call HtmlDecode on it. Replace:
#Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName)
with the following:
#HttpUtility.HtmlDecode(Helpers.checkEmptyPreFill(queryinputvalue,"q4_1Property",queryloandata.LoanName).ToString())
I would also suggest that you move some of the logic and data access code out of your view and into a controller but this should give you the result that you'e after.

Why are my inputs not resetting?

The below code generates several forms depending on data returned from the server. Everything generates fine, but after clicking on an AnswerOpenQuestion button the input does not clear/reset. What's going on here?
angularJs code:
var availableInterviewController = function($scope, $http) {
// define initial model
$scope.interviews = [];
// retrieve available interviews
$http.get('/api/UserInterviewsApi/AvailableInterviews')
.success(function(data) {
// update interviews
$scope.interviews = [];
$scope.interviews = data;
});
// define open question answer selection
$scope.Answer = "";
// define multiple choice selection
$scope.selectedChoice = "";
// define answer open question button
$scope.AnswerOpenQuestion = function() {
$scope.Answer = ans;
alert(q.Question + ' and ' + $scope.Answer);
$scope.Answer = ''; // <---This is not clearing/resetting the HTML form inputs
};
// define answer multiple choice button
$scope.AnswerMultipleChoice = function() {
//
};
};
// assign the new controller to the main angular app
myAngApp.controller('availableInterviewCtrl', availableInterviewController);
Html code:
<form class="form-group" ng-repeat="q in inter.Questions">
<fieldset style="display: inline-block;">
<legend>Question {{$index + 1}}</legend>
<!--Open Ended-->
<div class="form-group" ng-show="q.MultipleChoices.length === 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong><br />
</label>
<input name="openQuestion" id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="Answer" />
<button ng-click="AnswerOpenQuestion()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
<!--Multiple Choice Question-->
<div class="form-group" ng-show="q.MultipleChoices.length > 0">
<label for="{{'quest-' + $index}}">
<strong class="text-info">{{q.Question}}</strong>
</label>
<div>
Select an answer:
<label ng-repeat="x in q.MultipleChoices">
<input name="currentChoice" type="radio" value="{{x.Id}}"
ng-model="selectedChoice" />
{{x.Choice}}
</label>
<button ng-click="AnswerMultipleChoice()">Answer</button><br />
<span class="text-info">
asked by {{q.AskedByUserName ==
'Administrator' ? 'staff' : q.AskedByUserName}}
</span>
</div>
</div>
</fieldset>
</form>
UPDATE - Solution
AngularJs:
// define open question answer selection
$scope.OpenAnswer = { Answer: '' };
// define answer open question button
$scope.AnswerOpenQuestion = function (q, ans) {
$scope.OpenAnswer.Answer = ans;
alert(q.Question + ' and ' + $scope.OpenAnswer.Answer);
// clear the input
$scope.OpenAnswer.Answer = '';
};
Html:
<input id="{{'quest-' + $index}}" type="text"
class="form-control" ng-model="OpenAnswer.Answer" />
Don't use the scope as a model instead make an object that wraps the data model and assign it to a property of the scope.
$scope.myModel = {Answer:''}
Also don't use value in most cases ngmodel is all you need for two way binding.
In js strings are immutable so the original reference is not being updated instead a new string is being made, the digest cycle won't see this as a change to the original string.

knockout template parsing of json data is not working

Please check this link is not working, i have no idea what is wrong in my code.
I am trying to create a blog application, which have title, description and comments, but i am not getting proper output.
<h4>Title</h4>
<label data-bind="value: title" />
<h4>Description</h4>
<label data-bind="value: description" />
<h4>Comments</h4>
<p data-bind="foreach: comments">
<label data-bind="value: commenter" /><br>
<label data-bind="value: comment" /><br>
</p>​
var data = {"title": "blog1",
"description": "Description1",
"comments": [{"commenter": "commenter1", "comment": "comment1"},
{"commenter": "commenter2", "comment": "comment2"},
{"commenter": "commenter3", "comment": "comment3"},
{"commenter": "commenter4", "comment": "comment4"}]};
function Comment(data) {
this.commenter = ko.observable(data.commenter);
this.comment = ko.observable(data.comment);
}
function BlogViewModel(data) {
var self = data;
self.title = data.title;
self.description = data.description;
self.comments = ko.observableArray(ko.utils.arrayMap(data.comments, function (com) {
return new Comment(com.commenter, com.comment);
}));
}
ko.applyBindings(new BlogViewModel(data));
​
You have multiple problems with your code some are related to KnockOut some of them are not:
Which are not related to KO:
In BlogViewModel the self variable should hold this not the data parameter: so it should be var self = this;
Your comment mapping is wrong: the new Comment(com.commenter, com.comment) should be new Comment(com)
Which are related to KO:
The value binding is used for input elements, you have labels so you need to use the text binding instead. E.g data-bind="text: title"
KO needs valid html. Because the self-closing label tag is not valid you need to add the closing tags to your labels e.g <label data-bind="text: description"></label>
Here is a working JSFiddle containg all the fixes.