How to bypass Form Action? - c#

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()
{
}
}
}

Related

Not getting the Total Amount(Without VAT)

Country: Bahrain( i am selecting)
Amount:1000
Bank charges: 100(i am entering)
Vat:5%(entering) result:50(autogenerate)
Discount:6%(entering) result:60(autogenerate)
Total:1070(autogenerate)
This is working fine.I am getting the Total(with VAT).
Country:India(i am selecting)
Amount:1000
Bank charges: 100(i am entering)
Discount:5%(entering) result:50(autogenerate)
Total:(here i am not getting the amount)(may be because i set the visibility of VAT field false)
Here i am hidding the field VAT by using vattr.Visible=false. What should i do in order to sort out this issue?
Code behind:
protected void lstCountryy_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstCountryy.SelectedItem.Text == "U.A.E" || lstCountryy.SelectedItem.Text == "BAHRAIN" || lstCountryy.SelectedItem.Text=="SAUDI ARABIA")
{
vattr.Visible = true;
trdeclaration.Visible = false;
}
else
{
vattr.Visible = false;
trdeclaration.Visible = true;
}
}
Javascript:
function calculate(amount) {
var bankcharge = document.getElementById("<%=txtBankCharge.ClientID%>").value;
var vat = document.getElementById("<%=txtvatt.ClientID%>").value;
var discount = document.getElementById("<%=txtDiscount.ClientID%>").value;
var sum = 0;
$(".amt").each(function () {
if (isNaN(this.value))
{
alert("Please enter numbers only");
return false;
}
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
if (bankcharge.length > 0) {
if (isNaN(bankcharge)) {
alert("Bank charge should be numbers only !!");
return false;
}
else {
sum = sum + parseFloat(bankcharge);
}
}
if (vat.length > 0)
{
if (isNaN(vat)) {
alert("VAT should be numbers only !!");
return false;
}
else {
sum = sum + parseFloat(vat);
}
}
if (discount.length > 0) {
if (isNaN(discount)) {
alert("Discount amount should be numbers only !!");
return false;
}
else {
sum = sum - parseFloat(discount);
}
}
var atemp = sum.toString().split(".");
if (atemp.length > 1) {
sum = sum.toFixed(2);
}
document.getElementById("<%=txtTotal.ClientID%>").value = sum;
document.getElementById("<%=txtAmountInWords.ClientID%>").value = convertNumberToWords(sum);
}
function vatCalc()//added by chetan
{
var sum = 0;
$(".amt").each(function () {
if (isNaN(this.value)) {
alert("Please enter numbers only");
return false;
}
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
var _txt2 = document.getElementById('<%= txtvat.ClientID %>');
var _txt3 = document.getElementById('<%= txtvatt.ClientID %>');
var t1=0, t2=0;
//if(_txt1.value != "") t1=_txt1.value;
if(_txt2.value != "") t2=_txt2.value;
_txt3.value = (sum * parseFloat(t2) )/ 100;
}
function discountCalc()
{
var sum = 0;
$(".amt").each(function () {
if (isNaN(this.value)) {
alert("Please enter numbers only");
return false;
}
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
var _txt2 = document.getElementById('<%= txtDiscountText.ClientID %>');
var _txt3 = document.getElementById('<%= txtDiscount.ClientID %>');
var t1=0, t2=0;
//if(_txt1.value != "") t1=_txt1.value;
if(_txt2.value != "") t2=_txt2.value;
_txt3.value = (sum * parseFloat(t2)) / 100;
}
The problem is here:
if (vat.length > 0)
{
if (isNaN(vat)) {
alert("VAT should be numbers only !!");
return false;
}
else {
sum = sum + parseFloat(vat);
}
}
I wanted to write this condition in such a way that when use selects bahrain,vat should be visible and should be calculated.
when user selects india,vat should be hidden and will yield the total amount.
Finally i got solution.This w orked perfectly.
if (lstCountryy.SelectedValue == "U.A.E" || lstCountryy.SelectedValue == "BAHRAIN" || lstCountryy.SelectedValue == "SAUDI ARABIA")
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "float");
trdeclaration.Visible = false;
//txtvat.Enabled = true;
}
else
{
txtvat.Text = "";
txtvatt.Text = "";
txtBankCharge.Text = "";
txtDiscount.Text = "";
txtDiscountText.Text = "";
txtTotal.Text = "";
vattr.Style.Add("display", "none");
trdeclaration.Visible = true;
}

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?

Ion.Sound 1.1.0 JQuery javascript Response

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

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