AngularJS with JQuery validation - asp.net-mvc

I'm using angularjs to bring some data from server,
it's works perfectly.
Here is the code:
myAppcontroller("AgentCtrl", function ($scope, leadsService) {
$scope.showUsers = false;
$scope.cityName = { 'query': ''};
$scope.findAgent = function() {
leadsService.get("/api/usersapi/agents/" + $scope.cityName.query).then(function(out) {
$scope.agents = out;
$scope.showUsers = true;
$scope.selectedOption = $scope.agents[0];
});
};
$scope.init = function (cityName) {
$scope.cityName.query = cityName;
if ((typeof cityName !== "undefined")) {
$scope.findAgent();
}
};
$scope.$watch('cityName.query', function (newValue, oldValue) {
$scope.cityName.query.watch = newValue;
});
});
Now I have a validation error in Chrome... (I'm using jQuery validation).
Here is the code I'm using to disable this error:
$.validator.addMethod('date', function (value, element, params) {
if (this.optional(element)) {
return true;
}
var isValid = /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2} \d{2}:\d{1,2}:\d{1,2}$/.test(value);
alert(isValid);
return isValid;
}, '');
But when I use the jquery code angularjs stops working...
Some one have met this issue??? If so how to solve it?

Related

Unable to access Work Item Tracking services Azure DevOps Extensions

I am rendering extension on the Work item page using
<WebpageControlOptions AllowScript="true" ReloadOnParamChange="true">
<Link UrlRoot="http://.../extension/Validate-extension/1.0.69/assetbyname/workItemNotifications.html"/>
</WebpageControlOptions>
Following is the html/js code:
var workItemID = 0;
VSS.init({
explicitNotifyLoaded: true,
usePlatformScripts: true
});
VSS.ready(function () {
var currentContext = VSS.getWebContext();
VSS.register(VSS.getContribution().id, function (context) {
return {
// event handlers, called when the active work item is loaded/unloaded/modified/saved
onFieldChanged: function (args) {
if (!changedFields[args.id]) {
changedFields[args.id] = [];
changedFieldCount[args.id] = 0;
}
$.each(args.changedFields, function (key, value) {
if (!changedFields[args.id][key]) {
changedFields[args.id][key] = value;
changedFieldCount[args.id]++;
}
});
},
onLoaded: function (args) {
console.log("OnloadNotification");
VSS.require(["TFS/WorkItemTracking/Services"], function (workItemServices) {
workItemServices.WorkItemFormService.getService().then(function (workItemFormSvc) {
if (workItemFormSvc.hasActiveWorkItem()) {
console.log("Active work item is available.");
workItemFormSvc.getFieldValues(["System.Id"]).then(
function (value) {
var val = JSON.stringify(value);
$.each(value, function (key, values) {
if(key == "System.Id"){
workItemID = values;
}
});
});
}
else {
console.log("Active work item is NOT available.");
}
});
});
},
onUnloaded: function (args) {
},
onSaved: function (args) {
changedFieldCount[args.id] = 0;
changedFields[args.id] = [];
},
onReset: function (args) {
changedFieldCount[args.id] = 0;
changedFields[args.id] = [];
},
onRefreshed: function (args) {
changedFieldCount[args.id] = 0;
changedFields[args.id] = [];
}
};
});
VSS.notifyLoadSucceeded();
});
$(document).ready(function () {
$("#btnValidate").click(function () {
var getResponse = ValidateUser();
VSS.require(["TFS/WorkItemTracking/Services"], function (_WorkItemServices) {
var wiServiceNew = _WorkItemServices.WorkItemFormService.getService();
wiServiceNew.setFieldValue("System.Title", "Title set from your group extension!");
});
});
});
2 things which I am trying to achieve
After button click event to validate user, I have to access the Work Item fields after successful validation. Unable to access _WorkItemServices.
Not able to to get the Work Item fields.
When I set workItemID variable OnLoad event, it resets to 0 when a tab is clicked, value is not getting retained which is set OnLoad.
You may try to interact with the IWorkItemFormService service. For example:
import {
IWorkItemChangedArgs,
IWorkItemFieldChangedArgs,
IWorkItemFormService,
IWorkItemLoadedArgs,
WorkItemTrackingServiceIds
} from "azure-devops-extension-api/WorkItemTracking";
Check the sample here:
https://github.com/microsoft/azure-devops-extension-sample/blob/master/src/Samples/WorkItemFormGroup/WorkItemFormGroup.tsx

Passing String parameter Value Through angular Service parameter Value is Automatically Appends Some Special Character

Here's my Angular controller
//Save And Update
$scope.AddUpdateBusinessType = function() {
var businessType = {
Code: $scope.businessCode,
BusiType: $scope.businessType
};
var getBusinessTypeAction = $scope.BusinessTypeAction;
if (getBusinessTypeAction == "Update") {
businessType.BusinessTypeId = $scope.businessTypeId;
var getBusinessTypeData = businessTypeService.updateBusinessType(businessType);
getBusinessTypeData.then(function (msg) {
GetAllBusinessType();
$scope.ClearBusinessTypeForm();
alert("Record Updated Successful");
$scope.BusinessTypeAction = "";
$scope.divBusinessType = false;
}, function () {
alert('Error in Updating Record');
});
} else {
**// Save Section**
var getExistBusinessCode = businessTypeService.checkBusinessTypeCode(businessType.Code);
getExistBusinessCode.then(function (businessTypeCode) {
debugger;
if (businessTypeCode == true) {
alert('Business Type Code Already Exist');
} else {
debugger;
var getBusinessTypeData = businessTypeService.addBusinessType(businessType);
getBusinessTypeData.then(function (msg) {
GetAllBusinessType();
$scope.ClearBusinessTypeForm();
alert("Record Added Successful");
$scope.divBusinessType = false;
}, function () {
alert("Error Occured In Saving Data");
});
}
},function() {
alert('Error Occured While Checking Records');
});
}
}
In the above code Save Section I am trying to check if a value is exists in a database so I'm passing a string value to: checkBusinessTypeCode(businessType.Code) Service.When I Debug and See Value its Seems Normal.
Here's My Service:
//Check Business Code
this.checkBusinessTypeCode = function (businessTypeCode) {
debugger;
var response = $http({
method: "post",
url: "/BusinessType/CheckBusinessTypeDetailByCode",
params: {
businessTypeCode: JSON.stringify(businessTypeCode)
}
});
return response;
}
But when Passing To Controller string value I get some unexpected behavior.
two \\ always appear automatically
example
"\"stringvalue\""
I'm Still Having Above Problem
but as a quick solution i did code as follows
public bool _CheckBusinessTypeDetailByCode(string businessTypeCode)
{
string bisCode = businessTypeCode.Replace("\"", "");
bool isExist;
isExist = _IBusinessTypeRepository.IsExist(x => x.IsActive && !x.IsDelete && x.Code == bisCode);
return isExist;
}
I don't know is it bad practice or not , any way it is solved my problem.
Before did this modification
string businessTypeCode always gives value as
"\"somevalue\""

Model Id passed through to Angular Ctrl

I have a MVV view that used the Controller below, I need to get the product Id, ie Model.Id through to the controller somehow.
I have tried the $scope.init but it is coming through as null when I am making the first Ajax call, I suspect that this ajax get is kicking off before the init is fired and setting the product id, so the ajax fails as the productId is null when the call is made. I am new to angular so if its a schoolboy error I apologise !.
Controller and HTML are shown below.
angular.module('askQuestions', [])
.controller('questionController', function ($scope, $http) {
$scope.loading = true;
$scope.addMode = false;
$scope.replyMode = false;
$scope.parentClicked = 0;
$scope.init = function (productId) {
//This function is sort of private constructor for controller
$scope.productId = productId;
$scope.getUrl = '/Api/GetProductQuestions/' + $scope.productId;
};
//Used to display the data
//$http.get('/Api/GetAllManufacturers?apiToken=6a5ce02e-0506-0a41-2f50-37327080662f').success(function (data) {
$http.get($scope.getUrl).success(function (data) {
$scope.questions = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading questions!";
$scope.loading = false;
// alert($scope.getUrl);
});
});
<div data-ng-app data-ng-controller="questionController" ng-init="init('#Model.Id')" class="container">
Your $http.get is evaluated in the instantiation of the controller. The instantiation is before your init, so the ajax call is already being made. You can easily fix this by wrapping your $http.get also in a function:
$scope.init = function (productId) {
//This function is sort of private constructor for controller
$scope.productId = productId;
$scope.getUrl = '/Api/GetProductQuestions/' + $scope.productId;
getData();
};
var getData = function() {
$http.get($scope.getUrl)
.success(function (data) {
// success
$scope.questions = data;
})
.error(function () {
// error
$scope.error = "An Error has occured while loading questions!";
})
.finally(function () {
// always
$scope.loading = false;
});
}

Posting form data from Partial view to controller using ajax

I have a jquery grid that has a list of Employee Records.To edit the records there is a link on each row.On click of that A jquery model popup opens and loads the partial view to show and edit the data.But on click of the button(custom button not the jquery model button) on the popup(that loads a partial view),the client side validation using dataAnnotation does not work. If I make a submit form like:-
$("#btnUpdate).submit(function (e) {
e.preventDefault();
var $form = $(this);
if ($form.valid()) {
//Add ajax call
}
});
Then after submit it redirects to:- { ../Employee/Edit/EmployeeId } where it shows a blank screen as I dont have any view for this.
I want that after the form post it should just refresh the jquery grid.
public PartialViewResult _CreateSupplier()
{
return PartialView(new Supplier());
}
[HttpPost]
public JsonResult _CreateSupplier(Supplier model)
{
//Validation
return Json(new
{
status = transactionStatus,
modelState = ModelState.GetModelErorrs()
}, JsonRequestBehavior.AllowGet);
}
Form post jquery method
$('#create-supplier').submit(function (e) {
e.preventDefault();
var $form = $(this);
if (!ModelIsValid($form))
return;
AjaxPost($form.serialize(), '#Url.Action("_CreateSupplier")', function (result) {
if (result.status == 0) {
$form[0].reset();
//Success
var grid = $("#gridSupplier").data("kendoGrid");
grid.dataSource.read();
} else if (result.status == 1)
AddFormErrors($form, result);
else if (result.status == 2)
//error;
});
});
Checking model method is valid and if invalid adding errors to form
function ModelIsValid(form) {
var validator = $(form).validate(); // obtain validator
var anyError = false;
form.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
return true;
}
function AddFormErrors(form, errors) {
for (var i = 0; i < errors.modelState.length; i++) {
for (var j = 0; j < errors.modelState[i].errors.length; j++) {
var val = $(form).find("[data-valmsg-for='" + errors.modelState[i].key + "']");
if (val.html().length > 0) {
$(form).find("[for='" + errors.modelState[i].key + "']").html(errors.modelState[i].errors[j]);
} else {
val.html('<span for="' + errors.modelState[i].key + '" generated="true" class="" style="">' + errors.modelState[i].errors[j] + '</span>');
}
}
}
}
Ajax post method:
function AjaxPost(postData, url, callback) {
$.ajax({
url: url,
type: 'POST',
data: postData,
dataType: 'json',
success: function (result) {
if (callback) callback(result);
}
});
}
And last c# generic method which checks returns model state errors
public static IEnumerable<object> GetModelErorrs(this ModelStateDictionary modelState)
{
return modelState.Keys.Where(x => modelState[x].Errors.Count > 0)
.Select(x => new {
key = x,
errors = modelState[x].Errors.Select(y => y.ErrorMessage).ToArray()
});
}
Hope answer is useful...

How to call isValid() function in the viewmodel using knockout-validation

I have a viewmodel defined following:
var ViewModel = function() {
var self = this;
self.property1 = ko.observable().extend({ required: true });
self.property2 = ko.computed(function() {
return self.property1();
});
self.form_onsubmit = function (form) {
if (!self.isValid()) {
console.log("error");
}
return false;
};
};
$(function () {
ko.applyBindingsWithValidation(new ViewModel());
});
when i call the form_onsubmit function, an error occured:
TypeError: self.isValid is not a function
if (!self.isValid()) {
how to solve it, thanks^^^
add
self.errors = ko.validation.group(self);
to your viewmodel

Resources