Ion.Sound 1.1.0 JQuery javascript Response - c#

I have a question about a free plugin av on
http://ionden.com/a/plugins/ion.sound/en.html
My current javascript code look like this
(function ($) {
if($.ionSound) {
return;
}
var settings = {},
soundsNum,
canMp3,
url,
i,
sounds = {},
playing = false;
var createSound = function(name){
sounds[name] = new Audio();
canMp3 = sounds[name].canPlayType("audio/mp3");
if(canMp3 === "probably" || canMp3 === "maybe") {
url = settings.path + name + ".mp3";
} else {
url = settings.path + name + ".ogg";
}
$(sounds[name]).prop("src", url);
sounds[name].load();
sounds[name].volume = settings.volume;
};
var playSound = function(name){
var $sound = sounds[name],
playingInt;
if(typeof $sound === "object" && $sound !== null) {
if(!settings.multiPlay && !playing) {
$sound.play();
playing = true;
playingInt = setInterval(function(){
if($sound.ended) {
clearInterval(playingInt);
playing = false;
}
}, 250);
} else if(settings.multiPlay) {
if($sound.ended) {
$sound.play();
} else {
try {
$sound.currentTime = 0;
} catch (e) {}
$sound.play();
}
}
}
};
$.ionSound = function(options){
settings = $.extend({
sounds: [
"water_droplet"
],
path: "static/sounds/",
multiPlay: true,
volume: "0.5"
}, options);
soundsNum = settings.sounds.length;
if(typeof Audio === "function" || typeof Audio === "object") {
for(i = 0; i < soundsNum; i += 1){
createSound(settings.sounds[i]);
}
}
$.ionSound.play = function(name) {
playSound(name);
};
};
$.ionSound.destroy = function() {
for(i = 0; i < soundsNum; i += 1){
sounds[settings.sounds[i]] = null;
}
soundsNum = 0;
$.ionSound.play = function(){};
};
}(jQuery));
My question is the sound triggers slow (Interval response) does someone knows where this can be set/create to respond like 1 second or more even instant onclick of a button i need that else if a user click to fast the sound is not respond fast enough

hard to understand your question. You mean this?
$("#myButton").on("click", function(){
setTimeout(function(){
$.ionSound.play("button_tiny");
}, 1000); // 1 second delay
});

Related

Calling javascript function in Blazor for a Metronic Theme

I have been trying for sometime now to call the functions to this wizard on click but to no avail. Once i step through the code it works. If i take off the breakpoints, nothing. I've tried different calls but nothing works if i don't step through. My knowledge on js is not really that good.
C# Code:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JsRuntime.InvokeAsync<object>("KTWizard", "goTo(number)");
}
}
Javascript:
// plugin setup
var KTWizard = function(elementId, options) {
// Main object
var the = this;
var init = false;
// Get element object
var element = KTUtil.get(elementId);
var body = KTUtil.get('body');
if (!element) {
return;
}
// Default options
var defaultOptions = {
startStep: 1,
manualStepForward: false
};
////////////////////////////
// ** Private Methods ** //
////////////////////////////
var Plugin = {
/**
* Construct
*/
construct: function(options) {
if (KTUtil.data(element).has('wizard')) {
the = KTUtil.data(element).get('wizard');
} else {
// reset menu
Plugin.init(options);
// build menu
Plugin.build();
KTUtil.data(element).set('wizard', the);
}
return the;
},
/**
* Init wizard
*/
init: function(options) {
the.element = element;
the.events = [];
// merge default and user defined options
the.options = KTUtil.deepExtend({}, defaultOptions, options);
// Elements
the.steps = KTUtil.findAll(element, '[data-ktwizard-type="step"]');
the.btnSubmit = KTUtil.find(element, '[data-ktwizard-type="action-submit"]');
the.btnNext = KTUtil.find(element, '[data-ktwizard-type="action-next"]');
the.btnPrev = KTUtil.find(element, '[data-ktwizard-type="action-prev"]');
the.btnLast = KTUtil.find(element, '[data-ktwizard-type="action-last"]');
the.btnFirst = KTUtil.find(element, '[data-ktwizard-type="action-first"]');
// Variables
the.events = [];
the.currentStep = 1;
the.stopped = false;
the.totalSteps = the.steps.length;
// Init current step
if (the.options.startStep > 1) {
Plugin.goTo(the.options.startStep);
}
// Init UI
Plugin.updateUI();
},
/**
* Build Form Wizard
*/
build: function() {
// Next button event handler
KTUtil.addEvent(the.btnNext, 'click', function(e) {
e.preventDefault();
Plugin.goNext();
});
// Prev button event handler
KTUtil.addEvent(the.btnPrev, 'click', function(e) {
e.preventDefault();
Plugin.goPrev();
});
// First button event handler
KTUtil.addEvent(the.btnFirst, 'click', function(e) {
e.preventDefault();
Plugin.goFirst();
});
// Last button event handler
KTUtil.addEvent(the.btnLast, 'click', function(e) {
e.preventDefault();
Plugin.goLast();
});
KTUtil.on(element, 'a[data-ktwizard-type="step"]', 'click', function() {
var index = KTUtil.index(this) + 1;
if (index !== the.currentStep) {
Plugin.goTo(index);
}
});
},
/**
* Handles wizard click wizard
*/
goTo: function (number) {
// Skip if this step is already shown
if (number === the.currentStep || number > the.totalSteps || number < 0) {
return
}
// Validate step number
if (number) {
number = parseInt(number);
} else {
number = Plugin.getNextStep();
}
// Before next and prev events
var callback;
if (number > the.currentStep) {
callback = Plugin.eventTrigger('beforeNext');
} else {
callback = Plugin.eventTrigger('beforePrev');
}
// Skip if stopped
if (the.stopped === true) {
the.stopped = false;
return;
}
// Continue if no exit
if (callback !== false) {
// Before change
Plugin.eventTrigger('beforeChange');
// Set current step
the.currentStep = number;
Plugin.updateUI();
// Trigger change event
Plugin.eventTrigger('change');
}
// After next and prev events
if (number > the.startStep) {
Plugin.eventTrigger('afterNext');
} else {
Plugin.eventTrigger('afterPrev');
}
return the;
},
/**
* Cancel
*/
stop: function() {
the.stopped = true;
},
/**
* Resume
*/
start: function() {
the.stopped = false;
},
/**
* Check last step
*/
isLastStep: function() {
return the.currentStep === the.totalSteps;
},
/**
* Check first step
*/
isFirstStep: function() {
return the.currentStep === 1;
},
/**
* Check between step
*/
isBetweenStep: function() {
return Plugin.isLastStep() === false && Plugin.isFirstStep() === false;
},
/**
* Go to the next step
*/
goNext: function() {
return Plugin.goTo(Plugin.getNextStep());
},
/**
* Go to the prev step
*/
goPrev: function() {
return Plugin.goTo(Plugin.getPrevStep());
},
/**
* Go to the last step
*/
goLast: function() {
return Plugin.goTo(the.totalSteps);
},
/**
* Go to the first step
*/
goFirst: function() {
return Plugin.goTo(1);
},
/**
* Go to the first step
*/
updateUI: function() {
var stepType = '';
var index = the.currentStep - 1;
if (Plugin.isLastStep()) {
stepType = 'last';
} else if (Plugin.isFirstStep()) {
stepType = 'first';
} else {
stepType = 'between';
}
KTUtil.attr(the.element, 'data-ktwizard-state', stepType);
// Steps
var steps = KTUtil.findAll(the.element, '[data-ktwizard-type="step"]');
if (steps && steps.length > 0) {
for (var i = 0, len = steps.length; i < len; i++) {
if (i == index) {
KTUtil.attr(steps[i], 'data-ktwizard-state', 'current');
} else {
if (i < index) {
KTUtil.attr(steps[i], 'data-ktwizard-state', 'done');
} else {
KTUtil.attr(steps[i], 'data-ktwizard-state', 'pending');
}
}
}
}
// Steps Info
var stepsInfo = KTUtil.findAll(the.element, '[data-ktwizard-type="step-info"]');
if (stepsInfo &&stepsInfo.length > 0) {
for (var i = 0, len = stepsInfo.length; i < len; i++) {
if (i == index) {
KTUtil.attr(stepsInfo[i], 'data-ktwizard-state', 'current');
} else {
KTUtil.removeAttr(stepsInfo[i], 'data-ktwizard-state');
}
}
}
// Steps Content
var stepsContent = KTUtil.findAll(the.element, '[data-ktwizard-type="step-content"]');
if (stepsContent&& stepsContent.length > 0) {
for (var i = 0, len = stepsContent.length; i < len; i++) {
if (i == index) {
KTUtil.attr(stepsContent[i], 'data-ktwizard-state', 'current');
} else {
KTUtil.removeAttr(stepsContent[i], 'data-ktwizard-state');
}
}
}
},
/**
* Get next step
*/
getNextStep: function() {
if (the.totalSteps >= (the.currentStep + 1)) {
return the.currentStep + 1;
} else {
return the.totalSteps;
}
},
/**
* Get prev step
*/
getPrevStep: function() {
if ((the.currentStep - 1) >= 1) {
return the.currentStep - 1;
} else {
return 1;
}
},
/**
* Trigger events
*/
eventTrigger: function(name) {
//KTUtil.triggerCustomEvent(name);
for (var i = 0; i < the.events.length; i++) {
var event = the.events[i];
if (event.name == name) {
if (event.one == true) {
if (event.fired == false) {
the.events[i].fired = true;
event.handler.call(this, the);
}
} else {
event.handler.call(this, the);
}
}
}
},
addEvent: function(name, handler, one) {
the.events.push({
name: name,
handler: handler,
one: one,
fired: false
});
return the;
}
};
//////////////////////////
// ** Public Methods ** //
//////////////////////////
/**
* Set default options
*/
the.setDefaults = function(options) {
defaultOptions = options;
};
/**
* Go to the next step
*/
the.goNext = function() {
return Plugin.goNext();
};
/**
* Go to the prev step
*/
the.goPrev = function() {
return Plugin.goPrev();
};
/**
* Go to the last step
*/
the.goLast = function() {
return Plugin.goLast();
};
/**
* Cancel step
*/
the.stop = function() {
return Plugin.stop();
};
/**
* Resume step
*/
the.start = function() {
return Plugin.start();
};
/**
* Go to the first step
*/
the.goFirst = function() {
return Plugin.goFirst();
};
/**
* Go to a step
*/
the.goTo = function(number) {
return Plugin.goTo(number);
};
/**
* Get current step number
*/
the.getStep = function() {
return the.currentStep;
};
/**
* Check last step
*/
the.isLastStep = function() {
return Plugin.isLastStep();
};
/**
* Check first step
*/
the.isFirstStep = function() {
return Plugin.isFirstStep();
};
/**
* Attach event
*/
the.on = function(name, handler) {
return Plugin.addEvent(name, handler);
};
/**
* Attach event that will be fired once
*/
the.one = function(name, handler) {
return Plugin.addEvent(name, handler, true);
};
// Construct plugin
Plugin.construct.apply(the, [options]);
return the;
};
I was recently struggling with this and found the solution after digging into the scripts.bundle.js file for the metronic theme.
To make metronic work in blazor, place all the js imports in index.html / _Host.cshtml file like normal.
The event listeners will not be added to DOM elements upon loading a page since the DOM is rendered after the js files. To fix this locate KTUtil.ready(function(){...}) in scripts .bundle.js file which you previously added as an import in index.html file.
Take the function mentioned inside KTUtil.ready() and define a js function. Then using JSInterop call that function in OnAfterRenderAsync on a page which uses metronic componenets. That function is responsible for initializing all the event handlers
This is the scripts.bundle.js function you have to define in a JS file
function() {
////////////////////////////////////////////////////
// Layout Base Partials(mandatory for core layout)//
////////////////////////////////////////////////////
// Init Desktop & Mobile Headers
if (typeof KTLayoutHeader !== 'undefined') {
KTLayoutHeader.init('kt_header', 'kt_header_mobile');
}
// Init Header Menu
if (typeof KTLayoutHeaderMenu !== 'undefined') {
KTLayoutHeaderMenu.init('kt_header_menu', 'kt_header_menu_wrapper');
}
// Init Header Topbar For Mobile Mode
if (typeof KTLayoutHeaderTopbar !== 'undefined') {
KTLayoutHeaderTopbar.init('kt_header_mobile_topbar_toggle');
}
// Init Brand Panel For Logo
if (typeof KTLayoutBrand !== 'undefined') {
KTLayoutBrand.init('kt_brand');
}
// Init Aside
if (typeof KTLayoutAside !== 'undefined') {
KTLayoutAside.init('kt_aside');
}
// Init Aside Menu Toggle
if (typeof KTLayoutAsideToggle !== 'undefined') {
KTLayoutAsideToggle.init('kt_aside_toggle');
}
// Init Aside Menu
if (typeof KTLayoutAsideMenu !== 'undefined') {
KTLayoutAsideMenu.init('kt_aside_menu');
}
// Init Subheader
if (typeof KTLayoutSubheader !== 'undefined') {
KTLayoutSubheader.init('kt_subheader');
}
// Init Content
if (typeof KTLayoutContent !== 'undefined') {
KTLayoutContent.init('kt_content');
}
// Init Footer
if (typeof KTLayoutFooter !== 'undefined') {
KTLayoutFooter.init('kt_footer');
}
//////////////////////////////////////////////
// Layout Extended Partials(optional to use)//
//////////////////////////////////////////////
// Init Scrolltop
if (typeof KTLayoutScrolltop !== 'undefined') {
KTLayoutScrolltop.init('kt_scrolltop');
}
// Init Sticky Card
if (typeof KTLayoutStickyCard !== 'undefined') {
KTLayoutStickyCard.init('kt_page_sticky_card');
}
// Init Stretched Card
if (typeof KTLayoutStretchedCard !== 'undefined') {
KTLayoutStretchedCard.init('kt_page_stretched_card');
}
// Init Code Highlighter & Preview Blocks(used to demonstrate the theme features)
if (typeof KTLayoutExamples !== 'undefined') {
KTLayoutExamples.init();
}
// Init Demo Selection Panel
if (typeof KTLayoutDemoPanel !== 'undefined') {
KTLayoutDemoPanel.init('kt_demo_panel');
}
// Init Chat App(quick modal chat)
if (typeof KTLayoutChat !== 'undefined') {
KTLayoutChat.init('kt_chat_modal');
}
// Init Quick Actions Offcanvas Panel
if (typeof KTLayoutQuickActions !== 'undefined') {
KTLayoutQuickActions.init('kt_quick_actions');
}
// Init Quick Notifications Offcanvas Panel
if (typeof KTLayoutQuickNotifications !== 'undefined') {
KTLayoutQuickNotifications.init('kt_quick_notifications');
}
// Init Quick Offcanvas Panel
if (typeof KTLayoutQuickPanel!== 'undefined') {
KTLayoutQuickPanel.init('kt_quick_panel');
}
// Init Quick User Panel
if (typeof KTLayoutQuickUser !== 'undefined') {
KTLayoutQuickUser.init('kt_quick_user');
}
// Init Quick Search Panel
if (typeof KTLayoutQuickSearch !== 'undefined') {
KTLayoutQuickSearch.init('kt_quick_search');
}
// Init Quick Cart Panel
if (typeof KTLayoutQuickCartPanel !== 'undefined') {
KTLayoutQuickCartPanel.init('kt_quick_cart');
}
// Init Search For Quick Search Dropdown
if (typeof KTLayoutSearch !== 'undefined') {
KTLayoutSearch().init('kt_quick_search_dropdown');
}
// Init Search For Quick Search Offcanvas Panel
if (typeof KTLayoutSearchOffcanvas !== 'undefined') {
KTLayoutSearchOffcanvas().init('kt_quick_search_offcanvas');
}
}
And this is how you call it,
protected override async Task OnAfterRenderAsync(bool firstRender) {
await JsRuntime.InvokeVoidAsync("metronicScript");
}
Try this:
await JsRuntime.InvokeAsync<object>("KTWizard.goTo", 2);
2 is basically the number you want to pass to JS, you also need to make sure that KTWizard is already declared and created part of window object, let me know if it doesn't work.

How to bypass Form Action?

I am trying to bypass my form action="WFMSWI.aspx" , my form is working perfectly on my system but when i am testing on server the form comes through a proprietary software which provides database and inputs the form action automatically, which i not allowing my C# code to trigger. I tried using J query ajax but in URL it cannot the method because they change the URL too, if I put anything action like action="#" they change it no matter what.What can do to bypass it and that my method triggers instead of it. i also tried using Handler but nothing is working. Everything is working perfectly in local system and in server too it doesn't show any error it just fires form action rather than my c# code.
Form Action:
<form action="WFMSWI.aspx" id="form1" runat="server" method="post" name="form1">
Form Button:
<input type="button" ID="submit" class="btn btn-success" value="Approve" />
<button id="hiddenButton" runat="server" onserverclick="btnClick_Click" style="display:none;" ></button>
Java Script :
<script type="text/javascript">
var isEmpty = function (element) {
if ($("#" + element).val() == "" || $("#" + element).val() == null) {
return true;
} else {
return false;
}
};
var arrayCheck = function (array) {
for (var i = 0; i < array.length; i++) {
if (array[i] == false) {
return false;
}
};
return true;
};
function arrayAssign(array, num) {
for (var i = 0; i < num; i++) {
array[i] = false;
};
return array;
};
function validationCheck(array, number, element) {
if (isEmpty(element)) {
$("#" + element).parent(".form-group").addClass("has-error");
array[number] = false;
} else {
$("#" + element).parent(".form-group").removeClass("has-error");
array[number] = true;
}
};
var pass1 = [];
$(document).ready(function () {
if ($.browser.msie) {
if (parseInt($.browser.version) < "9.0") {
alert("Sorry! This form does not support your current IE version, please use Firefox/Google Chrome to submit.");
}
}
var preSig = $('#stu-sig-bit').val();
$('#stu-sig').attr('src', preSig);
var fakeVari = $("#typea").val();
$("#esignature").jSignature({
"background-color": "transparent",
"decor-color": "transparent",
"color": "#1489FF",
});
$("#clear").click(function () {
$("#esignature").jSignature("reset");
});
$("input[type=text]").attr("readonly", true);
$("textarea1").attr("readonly", true);
//$("input[type=radio]").attr("disabled", "disabled");
$("#reject-reason").attr("readonly", false);
$("#submit").click(function () {
$("#bitmap").val($("#esignature").jSignature("getData"));
arrayAssign(pass1, 2);
pass1[2] = false;
validationCheck(pass1, 0, "remaining_work");
validationCheck(pass1, 1, "deadline_date");
pass1[2] = true;
if (!arrayCheck(pass1)) {
return false;
}
else if ($("#esignature").jSignature("getData", "native").length == 0) {
alert("Please sign at bottom of the form.");
return false;
} else {
$("#iso_sig").val($("#bitmap").val());
$("#iso_decision").val("no");
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
$("#iso_date").val(temp);
var answer = confirm('Are you sure you want to approve the case?');
if (answer == true) {
document.getElementById('<%= hiddenButton.ClientID %>').click();
} else {
return false;
}
}
});
$("#reject-button").click(function () {
$("#bitmap").val($("#esignature").jSignature("getData"));
if (isEmpty("reject-reason")) {
alert("Please write down the reason why you reject the request.");
return false;
} else if ($("#esignature").jSignature("getData", "native").length == 0) {
alert("Please sign at bottom of the form.");
return false;
} else {
$("#iso_sig").val($("#bitmap").val());
$("#iso_decision").val("no");
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var temp = (month < 10 ? "0" : "") + month + "/" + (day < 10 ? "0" : "") + day + "/" + date.getFullYear();
$("#iso_date").val(temp);
var answer = confirm('Are you sure you want to reject the case?');
if (answer == true) {
} else {
return false;
}
}
});
});
</script>
Code Behind:
namespace HTMLtoPDF
{
public partial class HTMLtoPDF : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnClick_Click(object sender, EventArgs e)
{
DownloadAsPDF();
}
public void DownloadAsPDF()
{
}
}
}

Asp .NET Webforms is injecting code on WebResource.axd that I need to remove

I am trying to make a small WebForms app. However, I am having a huge problem because there is a code that is being inserted in the WebResource.axd file that is causing me problems.
However, I have no idea where this is happening. In addition to this web Forms is also injecting an old version of javascript that I no longer need.
Is there a way to disable WebResource.axd? If not where exactly is it getting the content from? I tried doing a global search but I could not find the code.
Here is the code that is causing me problems:
if (window.jQuery) {
(function ($) {
var dataValidationAttribute = "data-val",
dataValidationSummaryAttribute = "data-valsummary",
normalizedAttributes = { validationgroup: "validationGroup", focusonerror: "focusOnError" };
function getAttributesWithPrefix(element, prefix) {
var i,
attribute,
list = {},
attributes = element.attributes,
length = attributes.length,
prefixLength = prefix.length;
prefix = prefix.toLowerCase();
for (i = 0; i < length; i++) {
attribute = attributes[i];
if (attribute.specified && attribute.name.substr(0, prefixLength).toLowerCase() === prefix) {
list[attribute.name.substr(prefixLength)] = attribute.value;
}
}
return list;
}
function normalizeKey(key) {
key = key.toLowerCase();
return normalizedAttributes[key] === undefined ? key : normalizedAttributes[key];
}
function addValidationExpando(element) {
var attributes = getAttributesWithPrefix(element, dataValidationAttribute + "-");
$.each(attributes, function (key, value) {
element[normalizeKey(key)] = value;
});
}
function dispose(element) {
var index = $.inArray(element, Page_Validators);
if (index >= 0) {
Page_Validators.splice(index, 1);
}
}
function addNormalizedAttribute(name, normalizedName) {
normalizedAttributes[name.toLowerCase()] = normalizedName;
}
function parseSpecificAttribute(selector, attribute, validatorsArray) {
return $(selector).find("[" + attribute + "='true']").each(function (index, element) {
addValidationExpando(element);
element.dispose = function () { dispose(element); element.dispose = null; };
if ($.inArray(element, validatorsArray) === -1) {
validatorsArray.push(element);
}
}).length;
}
function parse(selector) {
var length = parseSpecificAttribute(selector, dataValidationAttribute, Page_Validators);
length += parseSpecificAttribute(selector, dataValidationSummaryAttribute, Page_ValidationSummaries);
return length;
}
function loadValidators() {
if (typeof (ValidatorOnLoad) === "function") {
ValidatorOnLoad();
}
if (typeof (ValidatorOnSubmit) === "undefined") {
window.ValidatorOnSubmit = function () {
return Page_ValidationActive ? ValidatorCommonOnSubmit() : true;
};
}
}
function registerUpdatePanel() {
if (window.Sys && Sys.WebForms && Sys.WebForms.PageRequestManager) {
var prm = Sys.WebForms.PageRequestManager.getInstance(),
postBackElement, endRequestHandler;
if (prm.get_isInAsyncPostBack()) {
endRequestHandler = function (sender, args) {
if (parse(document)) {
loadValidators();
}
prm.remove_endRequest(endRequestHandler);
endRequestHandler = null;
};
prm.add_endRequest(endRequestHandler);
}
prm.add_beginRequest(function (sender, args) {
postBackElement = args.get_postBackElement();
});
prm.add_pageLoaded(function (sender, args) {
var i, panels, valFound = 0;
if (typeof (postBackElement) === "undefined") {
return;
}
panels = args.get_panelsUpdated();
for (i = 0; i < panels.length; i++) {
valFound += parse(panels[i]);
}
panels = args.get_panelsCreated();
for (i = 0; i < panels.length; i++) {
valFound += parse(panels[i]);
}
if (valFound) {
loadValidators();
}
});
}
}
$(function () {
if (typeof (Page_Validators) === "undefined") {
window.Page_Validators = [];
}
if (typeof (Page_ValidationSummaries) === "undefined") {
window.Page_ValidationSummaries = [];
}
if (typeof (Page_ValidationActive) === "undefined") {
window.Page_ValidationActive = false;
}
$.WebFormValidator = {
addNormalizedAttribute: addNormalizedAttribute,
parse: parse
};
if (parse(document)) {
loadValidators();
}
registerUpdatePanel();
});
} (jQuery));
}
EDIT: This seems to be part of WebUIValidation.js. How do I prevent WebForms from injecting this file?

Validation type not achieved when calling ajax.post

I want to validate some fields before sending the model to my Action.
This is the textboxfor I want to validate
#Html.TextBoxFor(cModel => cModel.Value, new { id = "txtbLimit", #type = "int" })
#Html.ValidationMessageFor(cModel => cModel.Value)
And the ajax post:
$.post('#Url.Action("AddUpdateConfigs")',
{QueueMonitorConfigurationsID: ident, QueueMonitorConfigTypeName: $('#ddlConfigTypeName').val(), Threshold:$('#ddlThreshold').val(), QueueMonitorValueTypeName:$('#ddlValueTypeName').val(), Location: $('#txtbLocation').val(), Value: $('#txtbLimit').val()},
function(data){
if (!data.Success){
alert(data.Description);
}
else{
//$('#gridView').load('/Storage/gvConfigurations');
$.get('#Url.Action("gvConfigurations", "Storage")',null,function(data){$('#gridView').html(data);},'html');
}
},'json');
And the function it calls:
public JsonResult AddUpdateConfigs(StorageConfigurationModel modelbind)
{
//Take the list of configurations
IEnumerable<StorageConfigurationModel> configList = (IEnumerable<StorageConfigurationModel>)Session["ConfigurationList"];
//Loop
foreach (StorageConfigurationModel configModel in configList)
{
//Is it a duplicated entry?
if ((configModel.QueueMonitorConfigTypeName == modelbind.QueueMonitorConfigTypeName) && (configModel.Location == modelbind.Location) && (configModel.QueueMonitorValueTypeName == modelbind.QueueMonitorValueTypeName) && (configModel.Threshold == modelbind.Threshold))
{
//Found duplicated entry
return Json(new { Success = false, Description = "Duplicate entry" });
}
}
//If not duplicated, add it to DB
try
{
if (modelbind.Location.StartsWith("\\"))
{
DirectoryInfo dir = new DirectoryInfo(modelbind.Location);
if (dir.Exists)
{
int finalValue = 0;
int pathInt = 0;
int valueTypeInt = 0;
if (modelbind.QueueMonitorConfigTypeName == PathType.Path)
pathInt = 1;
else
pathInt = 2;
switch (modelbind.QueueMonitorValueTypeName)
{
case UnitType.Percentage:
valueTypeInt = 1;
break;
case UnitType.MB:
valueTypeInt = 2;
break;
case UnitType.GB:
valueTypeInt = 3;
break;
case UnitType.TB:
valueTypeInt = 4;
break;
case UnitType.Files:
valueTypeInt = 5;
break;
}
if (modelbind.Threshold == ThresholdType.Upper)
finalValue = modelbind.Value;
else
finalValue = Convert.ToInt32("-" + modelbind.Value);
Boolean result = false;
result = DAL.queryAddUpdateConfig(modelbind.QueueMonitorConfigurationsID, pathInt, modelbind.Location, finalValue, valueTypeInt);
return Json(new { Success = result, Description = (result) ? ((modelbind.QueueMonitorConfigurationsID == -1) ? "New data inserted" : "Data updated") : "Error in Data types" });
}
else
{
return Json(new { Success = false, Description = "Location Path is not correct" });
}
}
else
{
return Json(new { Success = false, Description = "Location Path has to be UNC path" });
}
}
catch (Exception j)
{
return Json(new { Success = false, Description = "Error: " + j });
}
}
It is smart enough to bing the model but not to make the validation.
If I put a string in the textboxfor where a value (int) should be, it converts it to 0 and not doing the validation.
I also have validation for the Location with a regular expression...again not working.
Anyone see anything wrong? Thank you
EDIT:
I have:
#using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "form" }))
{}
And this before the ajax post:
$('#form').validate();
I don't see checking in your code if ModelState.IsValid. Additionally you should invoke
$('form').validate();
to validate your form on client-side or even use Ajax.BeginForm.

how to display validation summary of an asp.net page using Javascript

I have one asp.net form.
In it i have many fields which are required.
I want to display validation summary of all fields at the end of the form.
I have already checked for valid values of input controls.
Now i only want is Summary.
Here is my code for valid data input
<script language="javascript" type="text/javascript">
function userCheck(uName) {
var uName = document.getElementById(uName);
var letters = /^[A-Za-z0-9]+$/;
if (uName.value.match(letters) && uName.value.length != 0) {
uName.style.border = "2px solid #008A2E";
return true;
}
else {
uName.value = uName.value.replace(/[\W]/g, '');
uName.style.border = "2px solid #ff0000";
uName.focus();
return false;
}
}
</script>
This is just one function for username check.
I have many more to deal with.
Is there any way to display summary from all fields at the last when submit button is pressed ?
below solution is not working.
function ddlcheck(ddlclg) {
var clg = document.getElementById(ddlclg.id);
var clgname = document.getElementById('<%= LblCollegeName.ClientID %>');
clgname.style.display = "block";
clgname.innerHTML = "Selected College : " + clg.options[clg.selectedIndex].value;
clg.style.border = "1px solid #008A2E";
if (clg.options[clg.selectedIndex].value == "Select") {
clgname.style.display = "none";
clg.style.border = "1px solid #ff0000";
validationhtml = validationhtml + "<b>*</b> College" + "</br>";
}
}
above code is for dropdownlist.
function select() {
var count = 0;
var chkSelectAll = document.getElementById('<%= ChkSelectAll.ClientID %>');
var chkList = document.getElementById('<%= chk.ClientID %>').getElementsByTagName("input");
for (var i = 0; i < chkList.length; i++) {
if (chkList[i].checked == true) {
count++;
}
}
if (count == chkList.length)
chkSelectAll.checked = true;
else {
chkSelectAll.checked = false;
}
}
above code is for selected check boxes.
create a div ( errorreport) at required location validation summary give it style as you needed
After that
<script language="javascript" type="text/javascript">
var validationhtml="";
function userCheck(uName) {
var uName = document.getElementById(uName);
var letters = /^[A-Za-z0-9]+$/;
if (uName.value.match(letters) && uName.value.length != 0) {
uName.style.border = "2px solid #008A2E";
return true;
} else {
uName.value = uName.value.replace(/[\W]/g, '');
uName.style.border = "2px solid #ff0000";
uName.focus();
validationhtml=validationhtml +"uname is not correct" ;
return false;
}
}
function validationsummary() {
// if using jquery
$(".errorreport").html(validationhtml);
//for javascript
document.getelementbyid("errorreport").innerHTML = validationhtml;
if(validationhtml == "") {
return true;
} else {
return false;
}
}
</script>
and call validationsummary() on submit button click

Categories