Knockout JS Validation not working - javascript

I am a newbie in Knockout JS. i want to apply validations in KO. i have used plugin knockout.validation.min.js . I have implemented it like this but not working
My View Model
$(document).ready(function myfunction() {
ko.applyBindings(new EmployeeKoViewModel());
})
var EmployeeKoViewModel = function () {
var self = this;
self.EmpId = ko.observable()
self.Name = ko.observable("").extend({ required: { message: "please enter employee name " } });
self.City = ko.observable("").extend({ required: { message: "please enter employee city " } });
self.Employees = ko.observableArray();
//GetEmployees();
var EmpData = {
EmpId: self.EmpId,
Name: self.Name,
City: self.City,
};
function GetEmployees() {
$.ajax({
type: "GET",
url: "/Employee/About",
}).done(function (data) {
self.Employees(data);
}).error(function (ex) {
alert("Error");
});
}
self.save = function () {
var EmployeeKoViewModel.errors = ko.validation.group(self);
if (!EmployeeKoViewModel.errors().length <= 0) {
EmployeeKoViewModel.errors.showAllMessages();
return false;
}
$.ajax({
type: "POST",
url: "/Employee/Save",
data: ko.toJSON(EmpData),
contentType: "application/json",
success: function (data) {
self.EmpId(data.EmpId);
GetEmployees();
},
error: function () {
alert("Failed");
}
});
//Ends Here
};
}
I have created a fiddle it is working when i comment GetEmployees() method but not working with it

At this line
var EmployeeKoViewModel.errors = ko.validation.group(self);
you are trying to create a variable, but the syntax is like creating an object with a property which is of course invalid. In order to fix this you can initialize your object first:
var EmployeeKoViewModel = {};
EmployeeKoViewModel.errors = ko.validation.group(self);
if (!EmployeeKoViewModel.errors().length <= 0) {
EmployeeKoViewModel.errors.showAllMessages();
return false;
}
Here is a working jsFiddle

Related

Why Ajax edit code not work properly? can you help me?

I m working on simple registration i have two forms one is registration another is city, When city is newly added it get added update perfectly but when i use city in registration form eg pune. pune will not get edited or updated, code written in ajax
function UpdateCity(Ids) {
debugger;
var Id = { Id: Ids }
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
}
})
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
}
debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
dataType: "text",
success: function (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
window.setTimeout(function () { location.reload() }, 3000)
}
})
})
}
Controller
public bool UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
return true;
}
catch (Exception Ex)
{
return false;
}
}
A few stabs in the dark here but, try changing your code to the following (with comments).
Controller:
// !! This is a POST transaction from ajax
[HttpPost]
// !! This should return something to ajax call
public JsonResult UpdateCity(City model, long CurrentUserId)
{
try
{
var city = db.Cities.Where(x => x.CityId == model.CityId && x.IsActive == true).FirstOrDefault();
if (city == null) return false;
city.CityName = model.CityName;
city.UpdateBy = CurrentUserId;
city.UpdateOn = DateTime.UtcNow;
db.SaveChanges();
// !! Change return type to Json
return Json(true);
}
catch (Exception Ex)
{
// !! Change return type to Json
return Json(false);
}
}
Script:
function UpdateCity(Ids) {
//debugger;
var Id = { Id: Ids };
$('#UpdateModel').modal('show');
$.ajax({
type: 'GET',
url: "/City/GetCityDetail",
data: Id,
dataType: "json",
success: function (city) {
$('#EditCityName').val(city.CityName);
$('#EditCityId').val(city.CityId);
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/GetCityDetail");
}
});
$('#UpdateCityButton').click(function () {
var model = {
CityName: $('#EditCityName').val(),
CityId: $('#EditCityId').val()
};
//debugger;
$.ajax({
type: 'POST',
url: "/City/UpdateCity",
data: model,
// !! Change return type to Json (return type from Server)
dataType: "json",
success: function (city) {
// !! Check result from server
if (city) {
$('#UpdateModel').modal('hide');
bootbox.alert("City updated");
// !! Why reload location?
// window.setTimeout(function () { location.reload(); }, 3000);
} else{
// !! Change this to something more suitable
alert("Server Error: /City/UpdateCity");
}
},
error: function () {
// !! Change this to something more suitable
alert("Error: /City/UpdateCity");
}
});
});
}
This should give you some more clues as to what's going on.

Applying knockout validation to an object

I have been trying to wrap my head around how I am supposed to apply knockout validation to my view model. In all of the examples I have found, validation is being applied to individual properties in the view model. However I was wondering if it is possible to apply validation to individual properties in a java script object? Here is my view model code:
$(document).ready(function () {
BindViewModel();
});
function ManageCustomerViewModel() {
var self = this;
self.searchResults = ko.mapping.fromJS([]);
self.customerCount = ko.observable();
self.Customer = ko.observable();
self.SearchOnKey = function (data, event) {
if (event.keyCode == 13 || event.keyCode == 9) {
self.CustomerSearch(data);
}
else {
return true;
}
};
self.AddCustomer = function () {
var cust = {
Id: 0,
FirstName: "",
LastName: "",
EmailAddress: "",
AlternatePhone: "",
BillingAddress: "",
BillingCity: "",
BillingState: "",
BillingZip: "",
PrimaryPhone: "",
ShippingAddress: "",
ShippingCity: "",
ShippingState: "",
ShippingZip: ""
}
self.Customer(cust);
};
self.UpdateCustomer = function () {
ShowLoading();
if (self.Customer().Id > 0) {
$.ajax("../api/CustomerAPI/UpdateCustomer", {
data: ko.mapping.toJSON(self.Customer),
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (e) {
HideLoading();
$('#Modal').modal('hide');
}
}).fail(function () { HideLoading() });
}
else {
$.ajax("../api/CustomerAPI/InsertNewCustomer", {
data: ko.mapping.toJSON(self.Customer),
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (e) {
HideLoading();
$('#Modal').modal('hide');
}
}).fail(function () { HideLoading() });
}
};
self.GetCustomerDetails = function (c) {
ShowLoading();
$.getJSON("../api/CustomerAPI/GetCustomerByID", { id: c.Id }, function (cust) {
self.Customer(cust);
HideLoading();
}).fail(function () { HideLoading() });
}
self.CustomerSearch = function (data) {
var first = $("#txtFirstName").val();
var last = $("#txtLastName").val();
var email = $("#txtEmail").val();
first = first.trim();
last = last.trim();
email = email.trim();
if (first == "" && last == "" & email == "") {
alert("Please enter at least one search value");
}
else {
ShowLoading();
$.getJSON("../api/CustomerAPI/GetCustomerSearchResults", { lastname: last, firstname: first, email: email }, function (allData) {
ko.mapping.fromJS(allData, self.searchResults);
self.customerCount(self.searchResults().length);
HideLoading();
}).fail(function () { HideLoading() });
}
};
}
function BindViewModel() {
ko.applyBindings(new ManageCustomerViewModel());
};
As you can see, I am using the Customer object to pass data back and forth. I would like to add validation to the properties of Customer. Is this doable or am I doing this wrong?

Does jQuery.ajax() not always work? Is it prone to miss-fire?

I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});

jquery validation error while checking department name

I have used the jquery validation for checking the department name is already exist in the specific organization. But its not returning the correct result. Please someone help me.
Here is my Jquery:
$(document).ready(function(){
var validator = $("#frmAddDepartment").validate({
errorElement:'div',
rules: {
organization:{
required:true
},
department: {
required: true,
allowChars:true,
//remote:$('#site_url').val()+"admin/department/check_department/"+$('#department').val()+"/"+$('#Organization').val(),
checkdeptname:true
}
},
messages: {
organization:{
required:languageArray['select_organization']
},
department:{
required:languageArray['enter_department'],
//remote:jQuery.format(languageArray['dept_exist'])
}
}
});
jQuery.validator.addMethod("allowChars", function(value, element) {
var filter = new RegExp(/[^a-zA-Z0-9\-& ]/);
if(!(filter.test(value)))
{
return true;
}else
return false;
},languageArray['please_enter_valid_chars']);
jQuery.validator.addMethod("checkdeptname", function(value, element) {
returnResult = false;
$.ajax({
url: $('#site_url').val()+"admin/department/check_department",
type: "GET",
data:{department:value,organization:$('#Organization').val()},
success: function (result)
{
returnResult = result;
alert(returnResult);
}
});
//$.get( $('#site_url').val()+"admin/department/check_department", { department:value,organization:$('#Organization').val() }, function(data){alert(data);returnResult = result;} );
return returnResult;
},languageArray['dept_exist']);});
PHP controller's function:
public function check_department()
{
$sql_query=$this->department_model->check_department();
if($sql_query>0)
{
echo "false";
}else
{
echo "true";
}
}
I think , in your php controller function you are returning ture/flase as String and on ajax success call back function your are comparing it with boolean ture/flase.

How to initialize knockoutjs view model with .ajax data

The following code works great with a hardcoded array (initialData1), however I need to use jquery .ajax (initialData) to initialize the model and when I do the model shows empty:
$(function () {
function wiTemplateInit(winame, description) {
this.WIName = winame
this.WIDescription = description
}
var initialData = new Array;
var initialData1 = [
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
];
console.log('gridrows:', initialData1);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
initialData.push(new wiTemplateInit(data.d[i].WiName,data.d[i].Description));
}
//console.log('gridrows:', initialData);
console.log('gridrows:', initialData);
}
});
var viewModel = function (iData) {
this.wiTemplates = ko.observableArray(iData);
};
ko.applyBindings(new viewModel(initialData));
});
I have been trying to work from the examples on the knockoutjs website, however most all the examples show hardcoded data being passed to the view model.
make sure your "WIWeb.asmx/GetTemplates" returns json array of objects with exact structure {WIName : '',WIDescription :''}
and try using something like this
function wiTemplateInit(winame, description)
{
var self = this;
self.WIName = winame;
self.WIDescription = description;
}
function ViewModel()
{
var self = this;
self.wiTemplates = ko.observableArray();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data)
{
var mappedTemplates = $.map(allData, function (item) { return new wiTemplateInit(item.WiName, item.Description) });
self.wiTemplates(mappedTemplates);
}
});
}
var vm = new ViewModel();
ko.applyBindings(vm);
If you show us your browser log we can say more about your problem ( Especially post and response ). I prepared you a simple example to show how you can load data with ajax , bind template , manipulate them with actions and save it.
Hope this'll help to fix your issue : http://jsfiddle.net/gurkavcu/KbrHX/
Summary :
// This is our item model
function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}
// Initial Data . This will send to server and echo back us again
var data = [new Item(1, 'One'),
new Item(2, 'Two'),
new Item(3, 'Three'),
new Item(4, 'Four'),
new Item(5, 'Five')]
// This is a sub model. You can encapsulate your items in this and write actions in it
var ListModel = function() {
var self = this;
this.items = ko.observableArray();
this.remove = function(data, parent) {
self.items.remove(data);
};
this.add = function() {
self.items.push(new Item(6, "Six"));
};
this.test = function(data, e) {
console.log(data);
console.log(data.name());
};
this.save = function() {
console.log(ko.mapping.toJSON(self.items));
};
}
// Here our viewModel only contains an empty listModel
function ViewModel() {
this.listModel = new ListModel();
};
var viewModel = new ViewModel();
$(function() {
$.post("/echo/json/", {
// Data send to server and echo back
json: $.toJSON(ko.mapping.toJS(data))
}, function(data) {
// Used mapping plugin to bind server result into listModel
// I suspect that your server result may contain JSON string then
// just change your code into this
// viewModel.listModel.items = ko.mapping.fromJSON(data);
viewModel.listModel.items = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
});
})

Categories

Resources