Applying knockout validation to an object - javascript

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?

Related

Only one alert for multiple execution in Ajax

I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}

Show partial view model using Ajax - ASP.NET C# AJAX JQuery

I am looking to show a modal, I have my Modals as partial classes, so if you select the class .js-verify-songs it loads up the partial _VerifySong . If however there is an error, it should load up the error partial _ErrorMessage. And finally if you select .js-reject-song it should load _RejectSong partial.
Any idea how I would do this, please?
to show errors. Currently I have this in my Controller to handle errors:
public partial class SongsManagementController : BaseController
{
private const string NoDataFound = "No data found.";
private const string InvalidDataPosted = "Invalid data posted";
private const string InvalidRequest = "Invalid request.";
private const string VerificationFailedUnexpectedError = "The following song failed to verify due to an unexpected error, please contact RightsApp support.";
private const string ConcurrencyError = "The following song failed to verify as another user has since changed its details.";
[HttpPost]
[Route("VerifyNewSongs")]
[AuthorizeTenancy(Roles = "super,administrator")]
public async Task<ActionResult> VerifyNewSongs(List<VerifySongViewModel> verifySongViewModels)
{
// Not AJAX method - refuse
if (!Request.IsAjaxRequest())
return RedirectToAction("NewSongs", "SongsManagement");
if (verifySongViewModels.NullOrEmpty())
{
// return error;
return Json(new JsonBaseModel
{
success = false,
message = InvalidRequest,
data = null,
errors = new List<string>
{
InvalidDataPosted
}
});
}
foreach (var verifySong in verifySongViewModels)
{
if (verifySong.WorkId == default(Guid) || verifySong.RowVersion == default(Guid))
{
return Json(new JsonBaseModel
{
success = false,
message = InvalidDataPosted,
data = null,
errors = new List<string>
{
$"Invalid data posted for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
var work = await _artistAccountService.GetWorkGraphAsync(verifySong.WorkId, includeWriterAmendments: true);
if (work == default(WorkGraphModels.Work))
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"No data found for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
if (work.VerifiedState != Domain.Enumerators.VerifiedStateType.NotVerified)
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"Song already verified.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
work.RowVersion = verifySong.RowVersion;
var workAndAmendment = new WorkGraphModels.WorkAndAmendment
{
Original = work,
Amendment = null
};
var verifiedState = await _artistAccountService.VerifyWorkGraphAsync(workAndAmendment, GetLoggedUserId());
if (!verifiedState.ValidationErrors.NullOrEmpty())
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else if (!verifiedState.DatabaseErrors.NullOrEmpty())
{
if (!verifiedState.FatalException)
{
// concurrency exception
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
ConcurrencyError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else
{
// fatal
return Json(new JsonBaseModel
{
success = false,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
}
}
return Json(new JsonBaseModel
{
success = true,
message = "All songs verified successfully."
});
}
};
}
This is my Main View:
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_SentricLayout.cshtml";
var actionName = ViewContext.RouteData.Values["Action"].ToString();
#* calc full account code *#
var fullAccountCode = Model.WorkUniqueCode;
ViewBag.Title = "New Songs";
}
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/datetimepicker")
<script language="javascript" type="text/javascript">
#* DOM ready? *#
$(function () {
addTableStylingScripts();
var selectFormDiv = $('.catalogSelector');
selectFormDiv.hide();
$(".records-selected").hide();
// clear all filter boxes and reset search.
$("#btnClear").click(function()
{
$("#newSongsSearch").find(':input').each(function ()
{
if (this.type === "text")
{
$(this).val("");
}
});
$("#btnSearch").click();
});
#* edit catalogue button *#
$('#changeCat').click(function () {
$('#errorContainer').hide();
var label = $('#catLabel');
if (label.is(":visible")) {
label.hide();
selectFormDiv.show();
$('#changeCat').addClass("active");
} else {
label.show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
}
});
#* edit dropdown *#
$("#catalogueSelect").on("change", function () {
#* change display on select change *#
$('#errorContainer').hide();
$('#catLabel').show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
#* set up ajax post to controller *#
var model = {
AccountCode: '#fullAccountCode',
CurrentAccountId: $('#currentAccountId').val(),
CurrentRowVersion: $('#currentRowVersion').val(),
NewCatalogueId: $('#catalogueSelect option:selected').val(),
Action: '#actionName'
};
$.ajax({
url: '#Url.Action("ChangeCatalogue", "ArtistAccount")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
#* ajax worked *#
if (result.ChangeStatus === "Success")
{
var newSelected = $('#catalogueSelect option:selected').text();
$('#catLabel').html(newSelected);
#* update dropdown context *#
var newSelectedId = $('#catalogueSelect option:selected').val();
$('#currentCatalogue').val(newSelectedId);
#* update rowversion *#
var newRowVersion = result.OldOrNewRowVersion;
$('#currentRowVersion').val(newRowVersion);
}
else
{
$('#errorContainer').show();
$('#errorMessage').html(result.ErrorMessage);
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
},
error: function () {
#* failed *#
$('#errorContainer').show();
$('#errorMessage').html('There was a server error, please contact the support desk on (+44) 0207 099 5991.');
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
});
});
function loadPartialPage(url) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: url,
type: 'GET',
cache: false,
success: function (result) {
$('.spinnerOverlay').addClass('hide');
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
}
function getSelectedWorks() {
var selectedWorks = $(".individual:checked");
var works = [];
$.each(selectedWorks, function (key, value) {
works.push(getSelectedWork(this));
});
return works;
}
// verify songs in bulk
$(document).on("click", ".js-verify-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
verifySongs(works);
});
// reject songs in bulk
$(document).on("click", ".js-reject-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
});
function getSelectedWork(element) {
var work = new Object();
work.WorkId = getRowData(element, "id");
work.RowVersion = getRowData(element, "rowversion");
work.UniqueCode = getRowData(element, "uniqueworkid");
work.SongTitle = getRowData(element, "songtitle");
return work;
}
// verify one song
$(document).on("click", ".js-verify-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
verifySongs(works);
});
// reject one song
$(document).on("click", ".js-reject-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
});
function verifySongs(songs) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: '#Url.Action("VerifyNewSongs", "SongsManagement")',
data: JSON.stringify(songs),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('.spinnerOverlay').addClass('hide');
if (result.success) {
loadPartialPage($(".paginate_button.active a").attr("href"));
}
},
error: function(error) {
$('.spinnerOverlay').addClass('hide');
}
});
}
#* Pagination Async Partial Handling *#
$(document).on("click",
"#indexPager a",
function() {
if ($(this).parent().hasClass('disabled') || $(this).parent().hasClass('active'))
return false;
loadPartialPage($(this).attr("href"));
return false;
});
$(document).on("change",
"#pageSizeSelector",
function() {
var selectedValue = $(this).val();
loadPartialPage(selectedValue);
return false;
});
#* Sorting Async Partial Handling *#
$(document).on("click",
"#tableHeader a",
function()
{
loadPartialPage($(this).attr("href"));
return false;
});
});
// Ensure that after paging and sorting ajax calls we re-bind
// the change event and hide the record count label.
$(document).ajaxComplete(function() {
$(".records-selected").hide();
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
});
// Search functions
$('.searchDivider').click(function (e) {
$('#searchFields').slideToggle();
var isSearchShown = $(this).find('.caret').hasClass("caret-up");
if (isSearchShown) {
$(this).children('span').replaceWith('<span class="bg-white">Search <b class="caret"></b></span>');
} else {
$(this).children('span')
.replaceWith('<span class="bg-white">Search <b class="caret caret-up"></b></span>');
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
$(window).resize(function () {
if ($(window).width() >= 1024) {
$('#searchFields').show();
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
// Checks individual checkboxes and displays the count
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
//Disable Top Verify Button if two or more checkboxes are selected.
$('.verify-btn').prop('disabled', true);
//Disable Action Button in the columns when more than one checkbox is selected
$('.table-btn').prop('disabled', false);
$(".individual").on("click", function () {
if ($(".individual:checked").length > 1) {
$('.table-btn').prop('disabled', true);
$('.verify-btn').prop('disabled', false);
}
else {
$('.table-btn').prop('disabled', false);
$('.verify-btn').prop('disabled', true);
}
});
// When one or more works are selected, will enable the top action menu.
// Will disable when none selected.
function determineActionButtonAvailability() {
if ($(".individual:checked").length > 1) {
$(".records-selected").show();
$("#selected").text($(".individual:checked").length);
$("#total").text($(".individual").length);
$(".verify-btn").prop('disabled', false);
if ($(".individual:checked").length > 1) {
}
}
else {
$(".records-selected").hide();
$('.table-btn').prop('disabled', false);
$(".verify-btn").prop('disabled', true);
}
}
// Enforce only numeric input in the Unique Id search textbox.
$(document).on("keydown", ".uniqueCodefield", function (e) {
var key = window.event ? e.keyCode : e.which;
var currentVal = $('.uniqueCodefield').val();
if (key === 8 || key === 9 || key === 13 || key === 37 || key === 39 || key === 35 || key === 36 || key === 46) {
return true;
} else if (key === 13) {
$('#newSongsSearch').validate();
if ($('#newSongsSearch').valid()) {
return true;
}
return false;
}
else if ((key < 48 || key > 57) && (key < 93 || key > 105)) {
return false;
} else if (currentVal.length >= 10) {
return false;
} else {
return true;
}
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
// Only perform the search if the search criteria is valid.
if (!$('#newSongsSearch').valid()) {
return false;
}
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel: {
WorkUniqueCode: $('#SongCode').val(),
SongTitle: $('#SongTitle').val(),
CatalogueUniqueCode: $('#CatalogueCode').val(),
CatalogueName: $('#CatalogueName').val(),
AccountUniqueCode: $('#AccountCode').val(),
AccountName: $('#AccountName').val()
}
};
$.ajax({
url: '#Url.Action("SearchNewSongs", "SongsManagement")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel : {
Name: $('#ContractNameSearch').val(),
ContractType: $('#ContractTypeSearch').val(),
CreatedBy: $('#CreatedBySearch').val(),
DateFrom : $('#DateFromSearch').val(),
DateTo : $('#DateToSearch').val()
}
};
$.ajax({
url: '#Url.Action("SearchContracts", "ClientSetup")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
</script>
#Scripts.Render("~/bundles/searchusers-autosuggest")
}
#section additionalStyles {
#Styles.Render("~/plugins/datatables/media/css/cssDatatables")
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-12">
<div class="panel panel-visible">
#Html.Partial("_NewSongsSearch", Model)
</div>
</div>
<div class="col-md-12">
<div class="panel panel-visible" id="tableContainer">
#Html.Partial("_NewSongsList", Model)
</div>
</div>
</article>
I am unsure though how I would show a list of error in my error partial view. Also how do you load a partial view with Ajax?
Currently you click verify and it loads the spinner, but I would like to load a partial view which is a modal. I’ve used partials because it’s what was decided. I’m just unsure how to get them to load using Ajax.

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.

Knockout JS Validation not working

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

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;
}
});

Categories

Resources