I am getting below error. Script has been attached in screenshot.
Please let me know the solution step by step.
<span class="left tooltip_link"><i class="fa fa-question-circle"></i></span>
</td>
</tr>
<tr>
<td class="text-right" width="200">
<label for="ContentPlaceHolder1_txtDescription" id="ContentPlaceHolder1_lblDescription">Description : </label>
</td>
<td>
<input name="ctl00$ContentPlaceHolder1$txtDescription" type="text" value="290802016 " maxlength="200" id="ContentPlaceHolder1_txtDescription" title="Enter Description" class="left" style="width:150px;" />
<span class="left tooltip_link"><i class="fa fa-question-circle"></i></span>
</td>
</tr>
</table>
</div>
<div class="clear">
<span id="ContentPlaceHolder1_rfvFileName" class="FontClass" style="display:none;"></span>
<span id="ContentPlaceHolder1_rfvValidFileName" class="FontClass" style="display:none;"></span>
<span id="ContentPlaceHolder1_rfvDesc" class="FontClass" style="display:none;"></span>
<span id="ContentPlaceHolder1_rfvValidDescription" class="FontClass" style="display:none;"></span>
</div>
</div>
</div>
<div class="mar-bot-10 clear">
<input type="submit" name="ctl00$ContentPlaceHolder1$btnAdd" value="Save" onclick="DataTool.ValidateAndToggleVisiblity(Page_ClientValidate('valForSchedule'));WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ContentPlaceHolder1$btnAdd", "", true, "valForSchedule", "", false, false))" id="ContentPlaceHolder1_btnAdd" title="Click to add new schedule" class="btn-clear" />
<input type="submit" name="ctl00$ContentPlaceHolder1$btnReset" value="Reset" id="ContentPlaceHolder1_btnReset" class="btn-clear" />
</div>
|0|hiddenField|__EVENTTARGET||0|hiddenField|__EVENTARGUMENT||452|hiddenField|__VIEWSTATE|/wEPBbgCSDRzSUFBQUFBQUFFQVB2UHlNL0thV2x1YW1CbWJHUm96cDhpeHBRR0lwZ1lnYVJBR3I4WWt4eG5abDVlYWxGR1NXNE9xNWROY1VsUmZsNjZuWDlBaUdkd3ZHTktibWFlalQ1VVRLRkd3U1pSSWFNb05jMVdYVmxkSVQ4dk9TY3pPZHRXM1NjLzNiKzBSRVBUV3QwT3lGUUFzbTMwRSsxU21KaEJock9BMUxQS1pwU1VGRmpwNjJjbUp4YVZGaGNVNk9VWGxHUVdKeFlVRk9zbDUrZW1NQW1CbExLSFpSWm5KdVdrWnFRd0NRUDU4a3pwS1V4eU1JWUNqS0VJWTZoQ3ZRRzJKU1Mxb29SVnhMa29OYkVrVmNIVktUaElJVGc1SXpXbE5DYzFKUVVBY3dqaFdRSUJBQUE9ZBpxCDqRIEungR80i/4HRMqKquCH|8|hiddenField|__VIEWSTATEGENERATOR|29933832|0|asyncPostBackControlIDs|||0|postBackControlIDs|||72|updatePanelIDs||tctl00$ContentPlaceHolder1$UpdatePanel1,ContentPlaceHolder1_UpdatePanel1|0|childUpdatePanelIDs|||71|panelsToRefreshIDs||ctl00$ContentPlaceHolder1$UpdatePanel1,ContentPlaceHolder1_UpdatePanel1|4|asyncPostBackTimeout||3600|18|formAction||./AddSchedule.aspx|12|pageTitle||Add Schedule|57|arrayDeclaration|Page_ValidationSummaries|document.getElementById("ContentPlaceHolder1_vldSummary")|58|arrayDeclaration|Page_Validators|document.getElementById("ContentPlaceHolder1_rfvFileName")|63|arrayDeclaration|Page_Validators|document.getElementById("ContentPlaceHolder1_rfvValidFileName")|54|arrayDeclaration|Page_Validators|document.getElementById("ContentPlaceHolder1_rfvDesc")|66|arrayDeclaration|Page_Validators|document.getElementById("ContentPlaceHolder1_rfvValidDescription")|194|scriptBlock|ScriptPath|/data/ScriptResource.axd?d=PIkWxDViaZE5PI1d5VC9u3oaIGXTi2MiwQcE00IlXrZtNMOjZbsuJ0QIWWw4HReSlnuBaIUBUZZbJyN_wtr3SycmM_LR-6SrO9qBExQmsX44PlsjganwUlmgp8zJhCIB2B9n40PUePHmOsGPVqSntMHbDWA1&t=1c6690ce|267|scriptStartupBlock|ScriptContentNoTags|
(function(id) {
var e = document.getElementById(id);
if (e) {
e.dispose = function() {
Array.remove(Page_ValidationSummaries, document.getElementById(id));
}
e = null;
}
})('ContentPlaceHolder1_vldSummary');
|281|scriptStartupBlock|ScriptContentNoTags|
var Page_ValidationActive = false;
if (typeof(ValidatorOnLoad) == "function") {
ValidatorOnLoad();
}
function ValidatorOnSubmit() {
if (Page_ValidationActive) {
return ValidatorCommonOnSubmit();
}
else {
return true;
}
}
|184|scriptStartupBlock|ScriptContentNoTags|
document.getElementById('ContentPlaceHolder1_rfvFileName').dispose = function() {
Array.remove(Page_Validators, document.getElementById('ContentPlaceHolder1_rfvFileName'));
}
|194|scriptStartupBlock|ScriptContentNoTags|
document.getElementById('ContentPlaceHolder1_rfvValidFileName').dispose = function() {
Array.remove(Page_Validators, document.getElementById('ContentPlaceHolder1_rfvValidFileName'));
}
|176|scriptStartupBlock|ScriptContentNoTags|
document.getElementById('ContentPlaceHolder1_rfvDesc').dispose = function() {
Array.remove(Page_Validators, document.getElementById('ContentPlaceHolder1_rfvDesc'));
}
|200|scriptStartupBlock|ScriptContentNoTags|
document.getElementById('ContentPlaceHolder1_rfvValidDescription').dispose = function() {
Array.remove(Page_Validators, document.getElementById('ContentPlaceHolder1_rfvValidDescription'));
}
|90|onSubmit||if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return false;|6|expando|document.getElementById('ContentPlaceHolder1_vldSummary')['displaymode']|"List"|16|expando|document.getElementById('ContentPlaceHolder1_vldSummary')['validationGroup']|"valForSchedule"|37|expando|document.getElementById('ContentPlaceHolder1_rfvFileName')['controltovalidate']|"ContentPlaceHolder1_txtScheduleName"|3|expando|document.getElementById('ContentPlaceHolder1_rfvFileName')['focusOnError']|"t"|27|expando|document.getElementById('ContentPlaceHolder1_rfvFileName')['errormessage']|"Schedule name is required"|6|expando|document.getElementById('ContentPlaceHolder1_rfvFileName')['display']|"None"|16|expando|document.getElementById('ContentPlaceHolder1_rfvFileName')['validationGroup']|"valForSchedule"|39|expando|document.getElementById('ContentPlaceHolder1_rfvFileName')['evaluationfunction']|"RequiredFieldValidatorEvaluateIsValid"|2|expando|document.getElementById('ContentPlaceHolder1_rfvFileName')['initialvalue']|""|37|expando|document.getElementById('ContentPlaceHolder1_rfvValidFileName')['controltovalidate']|"ContentPlaceHolder1_txtScheduleName"|3|expando|document.getElementById('ContentPlaceHolder1_rfvValidFileName')['focusOnError']|"t"|129|expando|document.getElementById('ContentPlaceHolder1_rfvValidFileName')['errormessage']|"Schedule name should only contain \u0027_\u0027 as special character and alpha numeric values with max lenght of 50 characters."|6|expando|document.getElementById('ContentPlaceHolder1_rfvValidFileName')['display']|"None"|16|expando|document.getElementById('ContentPlaceHolder1_rfvValidFileName')['validationGroup']|"valForSchedule"|43|expando|document.getElementById('ContentPlaceHolder1_rfvValidFileName')['evaluationfunction']|"RegularExpressionValidatorEvaluateIsValid"|23|expando|document.getElementById('ContentPlaceHolder1_rfvValidFileName')['validationexpression']|"^[A-Za-z0-9 _]{1,50}$"|36|expando|document.getElementById('ContentPlaceHolder1_rfvDesc')['controltovalidate']|"ContentPlaceHolder1_txtDescription"|3|expando|document.getElementById('ContentPlaceHolder1_rfvDesc')['focusOnError']|"t"|25|expando|document.getElementById('ContentPlaceHolder1_rfvDesc')['errormessage']|"Description is required"|6|expando|document.getElementById('ContentPlaceHolder1_rfvDesc')['display']|"None"|16|expando|document.getElementById('ContentPlaceHolder1_rfvDesc')['validationGroup']|"valForSchedule"|39|expando|document.getElementById('ContentPlaceHolder1_rfvDesc')['evaluationfunction']|"RequiredFieldValidatorEvaluateIsValid"|2|expando|document.getElementById('ContentPlaceHolder1_rfvDesc')['initialvalue']|""|36|expando|document.getElementById('ContentPlaceHolder1_rfvValidDescription')['controltovalidate']|"ContentPlaceHolder1_txtDescription"|3|expando|document.getElementById('ContentPlaceHolder1_rfvValidDescription')['focusOnError']|"t"|128|expando|document.getElementById('ContentPlaceHolder1_rfvValidDescription')['errormessage']|"Description should only contain \u0027_\u0027 as special character and alpha numeric values with max lenght of 200 characters."|6|expando|document.getElementById('ContentPlaceHolder1_rfvValidDescription')['display']|"None"|16|expando|document.getElementById('ContentPlaceHolder1_rfvValidDescription')['validationGroup']|"valForSchedule"|43|expando|document.getElementById('ContentPlaceHolder1_rfvValidDescription')['evaluationfunction']|"RegularExpressionValidatorEvaluateIsValid"|24|expando|document.getElementById('ContentPlaceHolder1_rfvValidDescription')['validationexpression']|"^[A-Za-z0-9 _]{1,200}$"|
You need to correlate at least __VIEWSTATE and __VIEWSTATEGENERATOR values with i.e. Regular Expression Extractor like you use timestamps for "ScheduleName" and "Description".
Search the web for "JMeter Correlation"- there is a plenty of information on the topic.
For .NET applications specifics you might also want to check out ASP.NET Login Testing with JMeter guide
Related
When i do dd($data); all data will shown but when i remove dd and simply submit my form then problem always come undefined index sku.
This is my controller for product attribute
public function addProductAttributes(Request $request){
if($request->isMethod('post')){
$data=$request->all();
foreach($data['sku'] as $key => $value){
if($value != null){
$attr = new ProductsAttribute();
$attr->product_id = $data['product_id'][$key];
$attr->sku = $data['sku'][$key];
$attr->stock=$data['stock'][$key];
$attr->price= $data['price'][$key];
$attr->size= $data['size'][$key];
$attr->status= $data['status'][$key];
$attr->save();
}
}
}
if($request->expectsJson()){
return response()->json([
'message'=>'Product has been Update Successfully',
]);
};
}
This is my Product Attribute Template. This is Dynamically Add / Remove input fields in Vue js so i can i add multiple data array
<form role="form" method="POST" #submit.prevent="addProductAttribute">
<table >
<tbody>
<tr v-for="(attr,index) in attribute" :key="index">
<td><input type="text" v-model="product_id" class="form-control"></td>
<td><input type="text" v-model="attr.sku" placeholder="SKU" class="form-control"></td>
<td><input type="text" v-model="attr.size" placeholder="Size" class="form-control"></td>
<td><input type="text" v-model="attr.stock" placeholder="Stock" class="form-control"></td>
<td><input type="text" v-model="attr.price" placeholder="Price" class="form-control"></td>
<td><input type="text" v-model="attr.status" placeholder="Status" class="form-control"></td>
<td><a #click="addAttribute()" v-show="index == attribute.length-1" title="Add More Product Attribute"><i class="fas fa-plus" style="color: #00b44e"></i></a> <a title="Remove" #click="removeAttribute(index)" v-show="index || ( !index && attribute.length > 1)"><i class="fas fa-minus" style="color: red"></i></a></td>
</tr>
</tbody>
<tfoot>
<tr><button type="submit" class=" btn-outline-primary btn-lg">Add</button></tr>
</tfoot>
</table>
</form>
and my Script file is
<script>
export default {
mounted() {
let app = this;
let id = app.$route.params.id;
app.product_id = id;
this.readProductAttribute();
},
data(){
return{
product_id:'',
product_name:'',
attributes:[],
product:'',
attribute:[
{
product_id:'',
sku:'',
price:'',
stock:'',
size:'',
status:'',
}
]
}
},
methods: {
removeAttribute(index){
this.attribute.splice(index, 1);
},
addAttribute(){
this.attribute.push({ size: '',sku:'',price:'',stock:'',status:'' });
},
addProductAttribute: function(e){
axios.post(`/admin/add-product-attribute`,{
myArray: this.attribute
})
.then(function(response){
console.log(response);
})
}
}
}
Your data lies within the key 'myArray' so changing the loop to the following should help on your error.
foreach($data['myArray'] as $key => $value){
The access logic for each attr is also flawed. You should only access it on their key, secondly it seems like product_id is not always there in your data, so you can use nullcoalescent to return empty string if key is not there.
$attr->product_id = $data['product_id'] ?? '';
$attr->sku = $data['sku'] ?? '';
$attr->stock=$data['stock'] ?? '';
$attr->price= $data['price'] ?? '';
$attr->size= $data['size'] ?? '';
$attr->status= $data['status'] ?? '';
Scenario 1
I am using v-for loop to print categories on button, now when I click on button it should show me the data related to that category. It is working fine when i use dropdown select category and click search and it displays all the related data.
But how to do it on button click event.
=====
Fetching categories in Button using v-for directives
<form #submit.prevent="product_info_form">
<div class="row mb-4">
<div class="col-3 px-2" v-for="(category, index) in categories" v-bind:value="category.slack" v-bind:key="index">
<button type="submit" class="btn btn-primary btn-lg btn-block py-4 margin-bottom" v-on:click="displaynumbers" v-bind:value="category.slack">{{ category.label }}</button>
</div>
<select name="category" v-model="category" class="form-control custom-select custom-select-lg">
<option value="">Filter by Category..</option>
<option v-for="(category, index) in categories" v-bind:value="category.slack" v-bind:key="index">
{{ category.label }}
</option>
</select>
</div>
</form>
In method I have written following code :
displaynumbers: function(e)
{
var buttonValue = e.target.value;
var formData = new FormData();
formData.append("access_token", window.settings.access_token);
//formData.append("barcode", this.barcode);
//formData.append("product_title", this.product_title);
if(buttonValue != '')
{
alert(buttonValue);
formData.append("product_category", this.buttonValue);
}
else
{
alert('Null vlaue passed');
}
axios.post('/api/get_product', formData).then((response) => {
this.product_processing = false;
console.log(response.data.data);
this.product_list = response.data.data;
if(this.barcode !='' && this.product_list.length == 1){
this.add_to_cart(this.product_list[0]);
this.barcode = '';
}
})
.catch((error) => {
console.log(error);
});
},
I have been unable to get the validation to work on an edit model-view that has data bound to it in the activate method of its view-model.
I have a created.ts which works on an object with the same fields. This file has almost the same code - the exception is that since this one is a create, no data needs to be loaded to it. In this case, the validation is working properly.
If I comment the code that loads the data for the edit model-view - in the activate method - the validation works properly.
Needless to say I am new to SPA, Aurelia and TypeScript and need some help!!
Below is the code in edit.ts
import { ContactRepository } from "./contactRepository";
import { autoinject } from "aurelia-framework";
import { ContactForEditDto } from "./contactForEditDto";
import { json } from "aurelia-fetch-client";
import { inject, NewInstance } from "aurelia-dependency-injection";
import { ValidationRules, ValidationControllerFactory, validateTrigger,
Validator } from "aurelia-validation";
#autoinject
export class Edit {
public saveStatusMessage: string;
public isSaved: number = -1;
private controller = null;
private validator = null;
public canSave: boolean = false;
constructor(public contactForEdit: ContactForEditDto, private repository:
ContactRepository, private controllerFactory: ValidationControllerFactory,
public contactFullName: string, validator: Validator) {
console.log("starting edit controller");
this.controller = controllerFactory.createForCurrentScope(validator);
this.controller.validateTrigger = validateTrigger.changeOrBlur;
this.validator = validator;
this.controller.subscribe(event => this.validateWhole());
ValidationRules
.ensure((c: ContactForEditDto) => c.contactFirstName)
.displayName("First Name")
.required().withMessage("\${$displayName} cannot be empty.")
.maxLength(50).withMessage("\${$displayName} cannot have more than 50 characters.")
.ensure((c: ContactForEditDto) => c.contactLastName)
.displayName("Last Name")
.required().withMessage("\${$displayName} cannot be empty.")
.maxLength(50).withMessage("\${$displayName} cannot have more than 50 characters.")
.ensure((c: ContactForEditDto) => c.contactEmailAddress)
.displayName("Email Address")
//.required().withMessage("\${$displayName} cannot be empty.")
.email().withMessage("\${$displayName} needs to be in a correct email address format.")
.maxLength(50).withMessage("\${$displayName} cannot have more than 50 characters.")
.ensure((c: ContactForEditDto) => c.contactPhoneNumber)
.displayName("Phone Number")
.required().withMessage("\${$displayName} cannot be empty.")
.maxLength(12).withMessage("\${$displayName} cannot have more than 12 characters.")
.matches(/\d{3}-\d{3}-\d{4}/).withMessage("'${$value}' is not a valid \${$displayName}. Please enter a phone in the format xxx-xxx-xxxx")
.on(ContactForEditDto);
}
// source https://www.jujens.eu/posts/en/2017/Jan/24/aurelia-validation/
workaround 3
validateWhole() {
this.validator.validateObject(this.contactForEdit)
.then(results => this.canSave = results.every(result => result.valid));
}
// Returning data from here because I can return a promise
// and let the router know when i have retrieved my initial data.
// Activate receives a params object as defined in the route.
activate(params) {
console.log("ACTIVATE ON EDIT PARAMS:" + params);
this.repository
.getById(params.id)
.then(data => {
console.log(data);
this.contactForEdit = data;
this.contactFullName = this.contactForEdit.contactLastName + ", " +
this.contactForEdit.contactFirstName; // This needs to come from a method
in
contact.
});
}
edit() {
this.saveStatusMessage = "";
this.isSaved = -1;
// This will be an edit
if (this.contactForEdit.contactId >= 1) {
this.repository
.update(this.contactForEdit)
.then(response => {
if (((response.status == 201) || (response.status == 204))
&& (response.ok == true)) {
this.isSaved = 1;
this.saveStatusMessage = "Successfully saved the contact";
}
else {
this.isSaved = 0;
//response.json().then(json => this.retVal = json);
//TODO: get more details about the error.
if (response.status == 400) {
this.saveStatusMessage = "Unable to save the contact. Please make sure that you entered correct values for every field and try again.";
}
else {
this.saveStatusMessage = "Unable to save the contact.";
}
}
});
}
}
clearContactFields() {
this.contactForEdit = new ContactForEditDto(-1, "", "", "", "");
}
}
Below is the code in edit.html
<template>
<form id="editContact" submit.delegate="edit()">
<!-- placeholder for status messages. If equal to 1 display it. If equals to
-1 or 1 hide this.-->
<div id="successStatusMessage" class.bind="isSaved == 1 ? 'visible' :
'hidden'">
<div id="divSuccessMessage" class="alert alert-success">
×
<!--<span class="glyphicon glyphicon glyphicon-ok" aria-hidden="true">
</span> TODO: How to get the glyphicon working? -->
<span class="sr-only"> Success:</span> ${saveStatusMessage}
</div>
</div>
<!-- placeholder for status messages. If equal to 0 is in error, so dislay error message. if equals to -1 or 1 hide this.-->
<div id="errorStatusMessage" class.bind="isSaved == 0 ? 'visible' : 'hidden'">
<!-- placeholder for status messages. -->
<div id="divErrorMessage" class="alert alert-danger">
×
<!-- <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> TODO: class="glyphicon glyphicon-exclamation-sign" how to get these in here for class? -->
<span class="sr-only"> Error:</span> ${saveStatusMessage}
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">
<!--<div if.bind="isCreate">
"Create a Contact"
</div>
<div if.bind="!isCreate">
Edit ${contactForEdit.contactFirstName}
</div>-->
${ "Edit " + contactFullName }
</div>
</div>
<div class="panel-body">
<div class="form-horizontal">
<div class="form-group" validation-errors.bind="editFirstNameErrors"
class.bind="editFirstNameErrors.length ? 'has-error' : ''">
<label class="control-label col-md-2">First Name: </label>
<div class="col-md-10">
<input type="text"
placeholder="First Name"
class="form-control"
value.bind="contactForEdit.contactFirstName & validate" required /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editFirstNameErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<div class="form-group" validation-errors.bind="editLastNameErrors"
class.bind="editLastNameErrors.length ? 'has-error' : ''">
<label class="control-label col-md-2">Last Name: </label>
<div class="col-md-10">
<input type="text"
placeholder="Last Name"
class="form-control"
value.bind="contactForEdit.contactLastName & validate" required /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editLastNameErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<div class="form-group" validation-errors.bind="emailErrors"
class.bind="editEmailErrors.length ? 'has-error' : ''">
<label for="emailAddress" class="control-label col-md-2">Email: </label>
<div class="col-md-10">
<input id="emailAddress"
type="text"
placeholder="Email Address (format: email#domain.com)"
class="form-control"
value.bind="contactForEdit.contactEmailAddress & validate" /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editEmailErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<div class="form-group" validation-errors.bind="editPhoneErrors"
class.bind="editPhoneErrors.length ? 'has-error' : ''">
<label class="control-label col-md-2">Phone: </label>
<div class="col-md-10">
<input type="text"
placeholder="Phone Number (format: xxx-xxx-xxxx)"
class="form-control"
value.bind="contactForEdit.contactPhoneNumber & validate" required /> <!-- NO ${} !!!-->
<span class="help-block" repeat.for="editErrorInfo of editPhoneErrors">
${editErrorInfo.error.message}
</span>
</div>
</div>
<button type="submit" class="btn btn-default ${canSave ? '' : 'disabled'}">
<!-- Look at click.dependent when there are child with buttons calling this.-->
Save
</button>
<!-- AA-10-17-17 - replaced with errors per input field. <ul for.bind="controller.errors">
<li repeat.for="error of controller.errors" style="color:red">
${error.message}
</li>
</ul>-->
</div>
</div>
</div>
</form>
<div>
<a route-href="route: home"
class="btn btn-default">
Back to list
</a>
</div>
</template>
I expect it's because of this code:
.getById(params.id)
.then(data => {
console.log(data);
this.contactForEdit = data;
your validation is against a ContactForEditDto object, but my guess is your repository is returning a JSON object cast to a ContactForEditDto, so it's not actually a class at all.
Try something like
console.log(data);
this.contactForEdit = new ContactForEditDto(data.id, data.firstname ..etc..);
or
console.log(data);
this.contactForEdit = Object.assign(new ContactForEditDto(), data);
We just had a similar problem and solved it by setting up our validations after assigning the remote data to our local field. In your code, you'd set up your validation rules after this.contactForEdit = data;
I have two questions regarding the following code.
1st problem: say I have four items in the array with ids of [1,2,4,5,7]
If I click on the sort and i have 2 items per page chosen then it will show me entries with id's of 1&2 or 5&7 as I toggle the reverse order.
So how can I get the table to just sort the items that are displayed in the paginated view?
2nd problem:
We are using a mixture of vue and some jquery from an admin template we purchased, But where it has <div class="checkbox checkbox-styled"> written in the code the check boxes will not render unless I put the Vue code in a setTimeout with an interval val of '100' or more.
And it generally just doesn't render stuff in jquery well if the item that relies on jquery is in a vue for loop.
Has anyone got an explanation for this?
Please note I've deleted as much out of this to keep the question as small as possible.
<div class="section-body">
<!-- BEGIN DATA TABLE START -->
<form class="form" role="form">
<div class="row">
<div class="col-lg-12">
<div id="" class="dataTables_wrapper no-footer">
<div class="table-responsive">
<table style="width: 100%" cellpadding="3">
<tr>
<td>
<div class="dataTables_length" id="entries_per_page">
<label>
<select name="entries_per_page" aria-controls="datatable" v-model="itemsPerPage">
<option value='2'>2</option>
<option value='20'>20</option>
<option value='30'>30</option>
</select>
entries per page
</label>
</div>
</td>
</tr>
</table>
<table class="table table-striped table-hover dataTable">
<thead>
<tr>
<th>
<div class="checkbox checkbox-styled">
<label>
<input type="checkbox" v-model="selectAll" :checked="allSelected" #click="selectAllCheckboxes">
</label>
</div>
</th>
<th v-bind:class="{'sorting': col.key !== sortKey, 'sorting_desc': col.key == sortKey && !isReversed, 'sorting_asc': col.key == sortKey && isReversed}" v-for="col in columns" #click.prevent="sort(col.key)">
<a href="#" v-cloak>${ col.label | capitalize}</a>
</th>
<th class="text-right">Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items | paginate | filterBy search">
<td width="57">
<div class="checkbox checkbox-styled">
<label>
<input type="checkbox" value="${ item.id }" v-model="cbIds" :checked="cbIds.indexOf(item.id) >= 0" />
</label>
</div>
</td>
<!-- !ENTITY_NAME TABLE COLUMNS START -->
<td v-cloak>${ item.id }</td>
<td v-cloak>${ item.title }</td>
<!-- !ENTITY_NAME TABLE COLUMNS END -->
<td class="text-right">
<button type="button" class="btn btn-icon-toggle" data-toggle="tooltip" data-placement="top" data-original-title="Edit row" #click="editItem(item)">
<i class="fa fa-pencil"></i></button>
<button type="button" class="btn btn-icon-toggle" data-toggle="tooltip" data-placement="top" data-original-title="Delete row" #click="deleteModalOpened(item)">
<i class="fa fa-trash-o"></i>
</button>
</td>
</tr>
</tbody>
</table>
<!-- PAGINATION START -->
<div class="dataTables_info" role="status" aria-live="polite" v-if="resultCount > 0" v-cloak>
Showing ${ currentCountFrom } to ${ currentCountTo } of ${ resultCount } entries
</div>
<div class="dataTables_paginate paging_simple_numbers" id="datatable_paginate" v-if="resultCount > 0">
<a class="paginate_button previous disabled" #click="previousPage()" v-if="currentPage==0">
<i class="fa fa-angle-left"></i>
</a>
<a class="paginate_button previous" #click="previousPage()" v-else>
<i class="fa fa-angle-left"></i>
</a>
<span v-for="pageNumber in totalPages">
<a class="paginate_button current" #click="setPage(pageNumber)" v-show="pageNumber == currentPage" v-cloak>${ pageNumber + 1 }</a>
<a class="paginate_button" #click="setPage(pageNumber)" v-show="pageNumber != currentPage" v-cloak>${ pageNumber + 1 }</a>
</span>
<a class="paginate_button next disabled" #click="nextPage()" v-if="currentPage == (totalPages - 1)">
<i class="fa fa-angle-right"></i>
</a>
<a class="paginate_button previous" #click="nextPage()" v-else>
<i class="fa fa-angle-right"></i>
</a>
</div>
<!-- PAGINATION END -->
</div>
</div>
</div>
</div>
</form>
<!-- BEGIN DATA TABLE END -->
</div>
<script>
Vue.config.delimiters = ['${', '}'];
new Vue({
el: '#app',
data: {
items: [],
columns: [
{
key: 'id' ,
label: 'id' ,
},
{
key: 'title' ,
label: 'title' ,
},
],
// ALL PAGINATION VARS
currentPage: 0,
itemsPerPage: 20,
resultCount: 0,
totalPages: 0,
currentCountFrom: 0,
currentCountTo: 0,
allSelected: false,
cbIds: [],
sortKey: '',
isReversed: false
},
computed: {
totalPages: function() {
return Math.ceil(this.resultCount / this.itemsPerPage);
},
currentCountFrom: function () {
return this.itemsPerPage * this.currentPage + 1;
},
currentCountTo: function () {
var to = (this.itemsPerPage * this.currentPage) + this.itemsPerPage;
return to > this.resultCount ? this.resultCount : to;
}
},
ready: function() {
this.pageUrl = '{{ path('items_ajax_list') }}';
this.getVueItems();
},
filters: {
paginate: function(list) {
this.resultCount = this.items.length;
if (this.currentPage >= this.totalPages) {
this.currentPage = Math.max(0, this.totalPages - 1);
}
var index = this.currentPage * this.itemsPerPage;
return this.items.slice(index, index + this.itemsPerPage);
}
},
methods : {
sort: function (column) {
if (column !== this.sortKey) {
this.sortKey = column;
this.items.sort(this.sortAlphaNum);
this.isReversed = false;
return;
}
this.reverse();
if (this.isReversed) {
this.isReversed = false;
}
else {
this.isReversed = true;
}
},
reverse: function () {this.items.reverse()},
sortAlphaNum: function (a, b) {
if (a[this.sortKey] === undefined) return;
if (b[this.sortKey] === undefined) return;
var cva = a[this.sortKey].toString().toLowerCase();
var cvb = b[this.sortKey].toString().toLowerCase();
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
var aA = cva.replace(reA, "");
var bA = cvb.replace(reA, "");
if(aA === bA) {
var aN = parseInt(cva.replace(reN, ""), 10);
var bN = parseInt(cvb.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
}
return aA > bA ? 1 : -1;
},
setPage: function(pageNumber) {this.currentPage = pageNumber},
nextPage: function () {
if (this.pageNumber + 1 >= this.currentPage) return;
this.setPage(this.currentPage + 1);
},
previousPage: function () {
if (this.currentPage == 0) return;
this.setPage(this.currentPage - 1);
},
getVueItems: function(page){
this.$http.get(this.pageUrl)
.then((response) => {
var res = JSON.parse(response.data);
this.$set('items', res);
});
},
}
});
</script>
Regarding your first problem, You can break the bigger array in smaller arrays, than show those on paginated way and sort the smaller array, I have created a fiddle to demo it here.
Following is code to break it in smaller arrays:
computed: {
chunks () {
var size = 2, smallarray = [];
for (var i= 0; i<this.data.length; i+=size) {
smallarray.push(this.data.slice(i,i+size))
}
return smallarray
}
}
Regarding your second problem, if the issue is that items is not getting properly populated after this.$http.get call, it can be due to wrong scope of this variable as well, which can be corrected like following:
getVueItems: function(page){
var self = this
this.$http.get(this.pageUrl)
.then((response) => {
var res = JSON.parse(response.data);
self.items = res;
});
},
I stumbled upon some code that has jQuery validation which is triggered after an ajax call that adds items to the DOM. The validation is working but the message is missing. just the field is highlighted. I have been playing with this for a while to get it to work, but so far no luck. Any ideas, thoughts appreciated.
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var otherIncomesCount = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var count = otherIncomesCount;
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
});
The validation succeeds for both required on additionalIncomeTypeIDMenu, and required and positive on amountTextBox, but the messages for both fail to show up:
function addOtherIncomeValidation(container) {
if (container) {
var additionalIncomeTypeIdMenu = $(container).find('select.other-income-type-id');
var amountTextBox = $(container).find('input.other-income-amount');
$(additionalIncomeTypeIdMenu).rules('add', {
required: true,
messages: {
required: 'Please select an income type'
}
});
$(amountTextBox).rules('add', {
required: true,
positive: true,
messages: { positive: 'must be positive number'
}
});
}
}
BTW The ajax call returns a partial EditorTemplate here, which you can see uses ValidationMessageFor.
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />#Html.ValidationMessageFor(x => x.AdditionalIncomeTypeId)
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />#Html.ValidationMessageFor(x => x.Amount)
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
HTML:
<div id="OtherIncome" class="applicant-section">
<h2 class="header2">Other Income</h2>
<div class="cornerForm">
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_0__Id" name="OtherIncome[0].Id" type="hidden" value="385" />
<label class="other-income-type-id-label" for="OtherIncome_0__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_0__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[0].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_0__AdditionalIncomeTypeId" name="OtherIncome[0].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option selected="selected" value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_0__Amount" name="OtherIncome[0].Amount" style="" type="text" value="0.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XNxxxxx753/385">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
<input class="other-income-id" data-val="true" data-val-number="The field Id must be a number." id="OtherIncome_1__Id" name="OtherIncome[1].Id" type="hidden" value="412" />
<label class="other-income-type-id-label" for="OtherIncome_1__AdditionalIncomeTypeId">Type:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].AdditionalIncomeTypeId" data-valmsg-replace="true"></span>
</td>
<td>
<label class="other-income-amount-label" for="OtherIncome_1__Amount">Amount:</label>
<br /><span class="field-validation-valid" data-valmsg-for="OtherIncome[1].Amount" data-valmsg-replace="true"></span>
</td>
<td> </td>
</tr>
<tr>
<td><select class="other-income-type-id" data-val="true" data-val-number="The field AdditionalIncomeTypeId must be a number." id="OtherIncome_1__AdditionalIncomeTypeId" name="OtherIncome[1].AdditionalIncomeTypeId"><option value="">--- Select One ---</option>
<option selected="selected" value="1">Alimony</option>
<option value="2">Child Support</option>
<option value="3">Disability</option>
<option value="4">Investments</option>
<option value="5">Rental Income</option>
<option value="6">Retirement</option>
<option value="7">Secondary Employment</option>
<option value="8">Separate Maintenance</option>
</select></td>
<td>
<input class="money other-income-amount" data-val="true" data-val-number="The field Amount must be a number." id="OtherIncome_1__Amount" name="OtherIncome[1].Amount" style="" type="text" value="22.00" />
</td>
<td>
<a class="remove-other-income-link" href="/Applicant/RemoveOtherIncome/XN42093753/412">Remove</a><img class="hide spinner" src="/Content/Images/ajax-loader_16x16.gif" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
</div>
<div id="additional-other-income"></div>
<input id="numberOfNewOtherIncomes" name="numberOfNewOtherIncomes" type="hidden" value="0" />
<input data-val="true" data-val-number="The field OriginalOtherIncomeTotal must be a number." id="OriginalOtherIncomeTotal" name="OriginalOtherIncomeTotal" type="hidden" value="22.0000" />
<a class="editable-link" href="/Applicant/AddOtherIncome?appId=XNxxxxx753" id="add-other-income-link">Add Other Income</a>
</div> </div>
Validation code:
$.validator.addMethod('positive', function(value, element) {
var check = true;
if (value < 0) {
check = false;
}
return this.optional(element) || check;
}, "Value must be a positive number."
);
I didn't think I would find my own answer but I did. first I have to apologize for my response to #Sparky with his request for rendered HTML. I did a "View page source" but that didn't include all the stuff which was added from the ajax call after the server delivered it's stuff. I suspect if I did include the extra DOM stuff at first, you would have pinpointed the issue sooner. My bad. Now on to the answer.
It appears that when injecting an EditorTemplate into the DOM in the way shown above, it doesn't properly process the page like you would expect in MVC. The code for #Html.ValidationMessageFor simply does not get parsed AT ALL. I am a little new to validation as you can see so I don't know why it behaves this way. To solve my problem here is what I did:
I updated my Editor Template slightly to look like this:
<div class="other-income" style="margin-bottom: 10px;">
<table class="other-income-table">
<tr>
<td>
#Html.HiddenFor(x => x.Id, new { #class = "other-income-id" })
#Html.LabelFor(x => x.AdditionalIncomeTypeId, "Type:", new { #class = "other-income-type-id-label" })
<br />
#Html.ValidationMessageFor(x=>x.AdditionalIncomeTypeId)
<span id="AdditionalIncomeTypeIdValidation"></span>
</td>
<td>
#Html.LabelFor(x => x.Amount, "Amount:", new { #class = "other-income-amount-label" })
<br />
#Html.ValidationMessageFor(x=>x.Amount)
<span id="amountValidation"></span>
</td>
<td> </td>
</tr>
<tr>
<td>#Html.DropDownListFor(x => x.AdditionalIncomeTypeId, new SelectList(Model.AdditionalIncomeTypes, "Value", "Text", Model.AdditionalIncomeTypeId), "--- Select One ---", new { #class = "other-income-type-id" })</td>
<td>
#Html.EditorFor(x => x.Amount, "Money", new { AdditionalClasses = "other-income-amount" })
</td>
<td>
#{
int? otherIncomeId = null;
var removeOtherIncomeLinkClasses = "remove-other-income-link";
if (Model.Id == 0)
{
removeOtherIncomeLinkClasses += " new-other-income";
}
else
{
otherIncomeId = Model.Id;
}
}
#Html.ActionLink("Remove", "RemoveOtherIncome", "Applicant", new { applicationId = Model.ApplicationId, otherIncomeId = otherIncomeId }, new { #class = removeOtherIncomeLinkClasses })<img class="hide spinner" src="#Url.Content("~/Content/Images/ajax-loader_16x16.gif")" alt="Deleting..." style="margin-left: 5px;" />
</td>
</tr>
</table>
Notice the new span tags, which is are added next to the #Html.ValidationMessageFor.
then in my success function from the ajax call in javascript I made these changes:
$('#add-other-income-link').click(function (event) {
event.preventDefault();
var count = $('#numberOfNewOtherIncomes').val();
$('div[hideCorner = yep]').show();
var url = $(this).attr('href');
if (url) {
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function (data) {
$('#additional-other-income').append(data);
var id = 0;
$('#additional-other-income').find('table.other-income-table').each(function (i, item) {
id = $(item).find('input.other-income-id');
var additionalIncomeTypeIdLabel = $(item).find('label.other-income-type-id-label');
var amountLabel = $(item).find('label.other-income-amount-label');
var additionalIncomeTypeIdMenu = $(item).find('select.other-income-type-id');
var amountTextBox = $(item).find('input.other-income-amount');
var amountValidation = $(item).find('#amountValidation');
var typeIdValidation = $(item).find('#AdditionalIncomeTypeIdValidation');
var idIndexer = 'OtherIncome_' + count + '__';
var nameIndexer = 'OtherIncome[' + count + '].';
var indexer = '[' + i + ']';
amountValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'Amount')
.attr('data-valmsg-replace','true');
typeIdValidation.attr('class', 'field-validation-valid')
.attr('data-valmsg-for', nameIndexer + 'AdditionalIncomeTypeId')
.attr('data-valmsg-replace','true');
id.attr('id', idIndexer + 'Id').attr('name', nameIndexer + 'Id');
additionalIncomeTypeIdLabel.attr('for', idIndexer + 'AdditionalIncomeTypeId');
amountLabel.attr('for', idIndexer + 'Amount');
additionalIncomeTypeIdMenu.attr('id', idIndexer + 'AdditionalIncomeTypeId').attr('name', nameIndexer + 'AdditionalIncomeTypeId');
amountTextBox.attr('id', idIndexer + 'Amount').attr('name', nameIndexer + 'Amount').attr('data-val', 'true');
++count;
addOtherIncomeValidation(item);
notice I am manually adding in the missing validation spans that were not rendering. Now the validation message shows up at validation! Yay. I am not sure however that this is the best fix. It looks and smells like a hack, but I got it to work. I am sure it can be done a better way. Thanks again for interaction and feedback.