Validation for AutoComplete in Kendo Batch editing - asp.net

I am using kendo Grid batch editing in which i have used AutoComplete through Editortemplate which is as follows:
#(Html.Kendo().AutoComplete()
.Name("AccountTransactionItemHead")
.DataTextField("Value_AccountTransactionItemHead")
//.DataValueField("HeaderID")
.HtmlAttributes(new { style = "width:250px" })
.Filter("contains")
//.AutoBind(true)
.Events(events => events.Select("HeadComboSelect"))
.MinLength(3)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetHeadForHeadGrid", "Cashbox");
})
.ServerFiltering(true);
})
)
Now i want the validation for this if I don't select any value in this and if i move to second column it must validate for this field that "please select the AutoComplete".
My Grid and ViewModel is as follows:
[Required(ErrorMessage="Please Enter Head")]
public string AccountTransactionItemHead { get; set; }
public int lkpQualifier { get; set; }
public string lkpQualifierType { get; set; }
[Required(ErrorMessage = "Please Enter Description")]
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Please Use letters only")]
public string AccountTransactionItemDescription { get; set; }
[Required(ErrorMessage = "Please Enter Currency")]
[RegularExpression(#"^[a-zA-Z]+$", ErrorMessage = "Please Use letters only")]
public string AccountTransactionItemCurrency { get; set; }
columns.Bound(p => p.AccountTransactionItemHead).Title("Head").EditorTemplateName("HeadAutoComplete").ClientTemplate("#=AccountTransactionItemHead#").Width(120);
columns.Bound(p => p.AccountTransactionItemQualifier).Title("Trade Type").EditorTemplateName("AccountTransactionItemTradeDropDown").ClientTemplate("#=AccountTransactionItemQualifier#" + "<input type='hidden' class='lkpQualifierType' value='#=data.AccountTransactionItemQualifier#' />").Width(100);
columns.Bound(p => p.TestHeader).ClientTemplate("#=TestHeader# <input type='hidden' class='AccountTransactionHeaderID' value='#=TestHeader#' />").Hidden(true);
columns.Bound(p => p.AccountTransactionItemDescription).Title("Description").Width(130).ClientTemplate("#= AccountTransactionItemDescription#" + "<input type='hidden' class='AccountTransactionItemDescription' value='#=data.AccountTransactionItemDescription#' />");
columns.Bound(p => p.AccountTransactionItemCurrency).Width(80).Title("Currency").EditorTemplateName("CurrencyAutoComplete").ClientTemplate("#= AccountTransactionItemCurrency#" + "<input type='hidden' class='AccountTransactionItemCurrency' value='#=data.AccountTransactionItemCurrency#' />");
columns.Bound(p => p.AmtTransact).Width(100).Title("Amt Trans").ClientTemplate("#= AmtTransact#" + "<input type='hidden' class='AmtTransact' value='#=data.AmtTransact#' />");
I need the Validation for First Column that is AccountTransactionItemHead.

Try using kendo validator..
1.//Grid Custom Validation
$("#GridName").kendoValidator({
rules: {
// custom rules
custom: function (input, params) {
if (input.is("[name=AccountTransactionItemHead]")) {
//If the input is AccountTransactionItemHead
var autoComplete= input.val()
//check value is null or empty
if(autoComplete==null || autoComplete=="")
retrun false; //trigger validation
}
//check for the rule attribute
return true;
}
},
messages: {
custom: function (input) {
// return the message text
return "please select the AutoComplete!";
}
}
})
Another Grid Validation
$("#GridName").kendoValidator({
rules: {
AccountTransactionItemHead: {
required: true,
productnamevalidation: function (input) {
if (input.is(" [name='AccountTransactionItemHead']") && input.val() == ""){return false; //tigger validation show message }
//else valition passed value is not null or empty
return true;
}//end of function
}// end of rules;
},
messages: {
productnamevalidation: function (input) {
// return the message text
return "please select the AutoComplete!";
}
}
})
answer using Kenod.Ui.Validator
//Add validation on Service rate Grid
(function ($, kendo) {
$.extend(true, kendo.ui.validator, {
rules: {
greaterdate: function (input) {
if (input.is("[data-val-greaterdate]") && input.val() != "") {
var date = kendo.parseDate(input.val()),
earlierDate = kendo.parseDate($("[name='" + input.attr("data-val-greaterdate-earlierdate") + "']").val());
return !date || !earlierDate || earlierDate.getTime() < date.getTime();
}
return true;
}
// custom rules
taskdate: function (input, params) {
if (input.is("[name=WorkOrderDetailsDate]")) {
//If the input is StartDate or EndDate
var container = $(input).closest("tr");
var tempTask = container.find("input[name=WorkOrderDetailsDate]").data("kendoDatePicker").value();
var tempWork = $("#workOrder_EstStartDate").val();
var workDate = kendo.parseDate(tempWork);
var taskDate = kendo.parseDate(tempTask);
if (taskDate < workDate) {
return false;
}
}
//check for the rule attribute
return true;
}
}, //end of rule
messages: {
greaterdate: function (input) {
return input.attr("data-val-greaterdate");
},
taskdate: function (input) {
return "Task date must be after work date!";
},
}
});
})(jQuery, kendo);

Related

test in react for date picker

`const handleDateChange = (value: any, employeeId: string, i: number) =\> {
if (selectedDate?.filter((e: any) =\> e.employeeId === employeeId).length \> 0) {
setSelectedDate(selectedDate.map((e: any) =\> {
if (e.employeeId === employeeId) {
return { ...e, dateOfBirth: value }
}
else {
return { ...e }
}
}))
}
else {
setSelectedDate([...selectedDate, { employeeId: employeeId, dateOfBirth: value }])
}
setIsDisabled(false);
};`
If this datepicker contains functionality that allows you to change a button's state, develop a test for it.

How to Update relational Table in Asp.net core Web Api

I create two table Project or Member and i create relational table of project and member table named as project member i want to Update data of that relational table i use angularjs as frontend
This is put method to update the table
[Route("api/updateProjectData")]
[HttpPut]
public IActionResult UpdateProjectData(Project project, ProjectMember projectMember)
{
// query
if (project.ProjectId != project.ProjectId)
{
return BadRequest("Id Mismatched");
}
try
{
_context.Entry(project).State = EntityState.Modified;
_context.SaveChanges();
var memberDetails = _context.ProjectMembers.FirstOrDefault(e => e.ProjectId == project.ProjectId);
_context.Entry(projectMember).State = EntityState.Modified;
_context.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProjectExists(project.ProjectId))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
private bool ProjectExists(int id)
{
return _context.Projects.Any(e => e.ProjectId == id);
}
This is My frontend Api
$scope.UpdateProjectInfo = (ProjectID) => {
console.log($scope.ProjectID);
console.log($scope.ProjectName);
console.log($scope.ProjectStartDate);
console.log($scope.ProjectEndDate);
console.log($scope.UserStartDate);
$http({
method: 'PUT',
url: 'https://localhost:44307/api/updateProjectData?ProjectId=' + $scope.ProjectID + "&ProjectName=" + $scope.ProjectName + "&Startdate=" + $scope.ProjectStartDate + "&Enddate=" + $scope.ProjectEndDate + "&Status=&UserId=" + $scope.ddlUser + "&RoleId=" + $scope.ddlRole + "&UserStartdate=" + $scope.UserStartDate + "",
// headers: {
// 'Content-type': 'application/json;charset=utf-8'
// }
})
.then(function (response) {
console.log('ResponseUpdated', response.data);
$scope.ProjectName = response.data[0].projectName;
$scope.ddlUser = response.data[0].firstName + " " + response.data[0].lastName;
$scope.ddlRole = response.data[0].roleName;
$scope.ProjectStartDate = response.data[0].startdate;
$scope.ProjectEndDate = response.data[0].enddate;
$scope.UserStartDate = response.data[0].userStartdate;
notify('success', 'Record Updated Successfully.', '');
$scope.closeAddProjectPopup();
}, function (rejection) {
notify('error', rejection.data, '');
});
I successfully update one table But i confused how i update the second one pls tell me how i update

How can I implement WooCommerce REST API "orderby" successfully?

I'm creating a mobile application using flutter and I'm currently trying to list products with the ability to sort them, but everytime I try to implement the "orderby" parameter, I get this error:
I/flutter ( 5187):
{
"code":"rest_invalid_param",
"message":"Invalid parameter(s): orderby",
"data":
{
"status":400,
"params":
{
"orderby":"orderby is not one of date, id, include, title, slug, price, popularity, and rating."
},
"details":
{
"orderby":
{
"code":"rest_not_in_enum",
"message":"orderby is not one of date, id, include, title, slug, price, popularity, and rating.",
"data":null
}
}
}
}
The code where I get the error:
Future<List<Product>> getProducts({
int pageNumber,
int pageSize,
String strSearch,
String tagName,
String categoryID,
String sortBy,
String sortOrder = "asc",
}) async {
List<Product> data = [];
try {
String parameter = "";
if (strSearch != null) {
parameter += "&search=$strSearch";
}
if (pageSize != null) {
parameter += "&per_page=$pageSize";
}
if (pageNumber != null) {
parameter += "&page=$pageNumber";
}
if (tagName != null) {
parameter += "&tag=$tagName";
}
if (categoryID != null) {
parameter += "&category=$categoryID";
}
if (sortBy != null) {
parameter += "&orderby=$sortBy";
}
if (sortOrder != null) {
parameter += "&order=$sortOrder";
}
String url = Config.url +
Config.productsURL +
"?consumer_key=${Config.key}&consumer_secret=${Config.secret}${parameter.toString()}";
var response = await Dio().get(
url,
options: Options(
headers: {
HttpHeaders.contentTypeHeader: "application/json",
},
),
);
if (response.statusCode == 200) {
data = (response.data as List)
.map(
(i) => Product.fromJson(i),
)
.toList();
}
} on DioError catch (e) {
print(e.response);
}
return data;
}
In a couple of other similar questions, I've been seeing that I need to add a filter looking like this:
add_filter( 'rest_product_collection_params', array( $this, 'filter_add_rest_orderby_params' ), 10, 1 );
add_filter( 'rest_product_cat_collection_params', array( $this, 'filter_add_rest_orderby_params' ), 10, 1 );
function filter_add_rest_orderby_params( $params ) {
$params['orderby']['enum'][] = 'menu_order';
return $params;
}
I wanted to try this, however, I'm not sure if this would work in my case, and does anyone know what specific file I am going to edit to add this filter? I can't seem to find where people put it. (I'm using Wordpress.)

Unable to store image url in Firestore

I successfully uploaded the image to firebase storage but I'm having trouble to store image url in firestore.
I received an error on console when trying to view the image:
core.js:6462 WARNING: sanitizing unsafe URL value
C:\fakepath\coke.jpg (see http://g.co/ng/security#xss)
GET unsafe:C:\fakepath\coke.jpg net::ERR_UNKNOWN_URL_SCHEME
Below is the html code: (details.page.html)
<!-- PRODUCT PICTURE INPUT -->
<ion-item>
<ion-label position="stacked">Product Picture</ion-label>
<ion-input accept="image/*" type="file" name="productPics" formControlName="productPics" (change)="showPreview($event)"></ion-input>
</ion-item>
Below is the typescript code: (details.page.ts)
ngOnInit() {
this.productForm = this.fb.group({
productPics: new FormControl('', Validators.compose([
Validators.required,
])),
});
this.resetForm();
}
showPreview(event: any) {
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.onload = (e: any) => this.imgSrc = e.target.result;
reader.readAsDataURL(event.target.files[0]);
this.selectedImage = event.target.files[0];
} else {
this.imgSrc = "./assets/default_image.jpg";
this.selectedImage = null;
}
}
async saveProduct(formValue) {
this.isSubmitted = true;
this.product.userId = this.authService.getAuth().currentUser.uid;
if (this.productId) {
try {
this.product.createdAt = new Date().getTime();
console.log('product add');
console.log(this.productForm.value);
var filePath = `${formValue.productCategory}/${this.selectedImage.name}${new Date().getTime()}`;
const fileRef = this.storage.ref(filePath);
this.storage.upload(filePath, this.selectedImage).snapshotChanges().pipe(
finalize(() => {
fileRef.getDownloadURL().subscribe((url) => {
formValue['productPics'] = url;
this.service.insertImageDetails(formValue);
this.resetForm();
})
})
).subscribe();
await this.productService.addProduct(this.product);
await this.loading.dismiss();
this.navCtrl.navigateBack('/vendor-tabs/home-vendor');
} catch (error) {
console.log('product dont add');
this.presentToast('Error trying to save');
}
}
}
Below is the service: (product.service.ts)
private productsCollection: AngularFirestoreCollection<Product>;
addProduct(product: Product) {
return this.productsCollection.add(product);
}
getProduct(id: string) {
return this.productsCollection.doc<Product>(id).valueChanges();
}
updateProduct(id: string, product: Product) {
return this.productsCollection.doc<Product>(id).update(product);
}
deleteProduct(id: string) {
return this.productsCollection.doc(id).delete();
}
insertImageDetails(image) {
this.productsCollection.add(image);
}

ModelState.Clear(); is not working?

Why am I not cleared form ? ModelState.Clear(); is not work! in updated form sends the data again. Tried many different solutions but all in vain, so hope to find here a solution to this problem. Help me please!
"Controller"
public ActionResult Yandex()
{
ViewData["sucsess"]=" ";
return View();
}
[HttpPost]
public ActionResult Yandex(LoginModel model)
{
if (model.option1)
{
md.Modules_Update(1,1);
ViewData["sucsess"] = "• Дані успішно збережені!";
}
else
{
md.Modules_Update(1, 0);
ViewData["sucsess"] = "• Дані успішно збережені!";
}
ModelState.Clear();
return View( );
}
"View"
#using (Html.BeginForm())
{
Settings exit = new Settings();
<span class="property">Модуль включений: </span>
<span class="property">Так</span>
if (exit.Modules(1).ToString() == "1")
{
#Html.RadioButtonFor(m => m.option1, true, new { #checked = "checked", id = "1", #class="radio" })
}
else
{
#Html.RadioButtonFor(m => m.option1, true, new { id = "1", #class="radio" })
}
<span class="property">Ні</span>
if (exit.Modules(1).ToString() == "0")
{
#Html.RadioButtonFor(m => m.option1, false, new { #checked = "checked", id = "0", #class="radio" })
}
else
{
#Html.RadioButtonFor(m => m.option1, false, new { id = "0", #class="radio" })
}
<input type="submit" value="Зберегти" class="save" />
}
<span class="property_col">#ViewData["sucsess"]</span>
Values are still present in the POST request. The proper way to do this is to redirect to your GET action:
[HttpPost]
public ActionResult Yandex(LoginModel model)
{
if (model.option1)
{
md.Modules_Update(1,1);
TempData["sucsess"] = "• Дані успішно збережені!";
}
else
{
md.Modules_Update(1, 0);
TempData["sucsess"] = "• Дані успішно збережені!";
}
return RedirectToAction("Yandex");
}
Also notice that I have used TempData to transport the message during the redirect. So you might need to adapt your view accordingly:
<span class="property_col">#TempData["sucsess"]</span>

Resources