Postback on ajax request only smartphone and tablet - c#

I wrote some code in a contact form in jquery to validate the form, and if the form is valid, send all data to another file that send email with all data, etc.
Now if i use that form on PC it works, but if I use the form on a tablet or a smartphone, both android and ios, my site does postback and the validate is ignored.
Here is the part of code that validates the form
$('#bottone_invia_messaggio').on("click", function () {
$("#formPrincipale").validate({
submitHandler: function () {
$('#bottone_invia_messaggio').val("Loading")
var urlContatti = "url of a site";
$.ajax({
type: "POST",
url: urlContatti,
success: function () {
$('#bottone_invia_messaggio').val("Messaggio inviato");
$('#bottone_invia_messaggio').addClass("btn-success");
$('#bottone_invia_messaggio').prop('disabled', true);
inviaContatto($("#Nome").val(), $("#Email").val(), $("#Telefono").val(), $("#Messaggio").val());
registraEmailDb($("#Email").val());
}
});
},
onkeyup: false,
onclick: false,
rules: {
ctl00$Nome: {
required: true,
minlength: 2
},
ctl00$Email: {
required: true,
email: true
},
ctl00$Telefono: {
required: true
},
ctl00$Messaggio: {
required: true,
minlength: 10
},
ctl00$Privacy: {
required: true
}
},
messages: {
ctl00$Nome: {
required: "Per favore inserisci il nome",
minlength: "Sembra troppo corto"
},
ctl00$Email: {
required: "Indicaci la tua email",
email: "Email non valida"
},
ctl00$Telefono: {
required: "Inserisci un numero di telefono"
},
ctl00$Messaggio: {
required: "",
minlength: "Il messaggio e' troppo corto"
},
ctl00$Privacy: {
required: "***"
}
},
errorPlacement: function (error, element) {
if (!$(element).parent().is("span")) error.insertBefore(element);
else error.insertAfter($(element).parent());
},
errorElement: "span",
highlight: function (element) {
$(element).parent().removeClass("valid").addClass("has-error");
$(element).removeClass("valid");
},
success: function (element) {
if (!($(element).parent().is("span") || $(element).is("span"))) $(element).parent().removeClass("has-error").addClass("valid");
console.log($(element).parent());
}
});
$("#formPrincipale").attr("novalidate", "");
});
Here is the part of html generated server-side by asp.net
<div id="Contatti" class="formContatti"><div class="row"><div class="col-lg-6"><div class="mb-1"><input name="ctl00$Nome" id="Nome" class="form-control" placeholder="Nome e Cognome*" type="text"></div><div class="mb-1"><input name="ctl00$Email" id="Email" class="form-control" placeholder="Indirizzo Email*" type="text"></div><div class="mb-1"><input name="ctl00$Telefono" id="Telefono" class="form-control" placeholder="Telefono*" type="text"></div></div><div class="col-lg-6"><textarea name="ctl00$Messaggio" rows="2" cols="20" id="Messaggio" class="form-control h-100" placeholder="Messaggio*"></textarea></div></div><div class="col-12 mt-1 text-left"><span><input id="Privacy" name="ctl00$Privacy" type="checkbox"><label for="Privacy">*Accetto i termini sulla <a class="no-decoration" href="/privacy-terms">privacy</a></label></span></div><div class="d-flex flex-row-reverse"><button id="bottone_invia_messaggio" class="btn coloreTasto mt-2">Invia il messaggio</button></div></div>
Sorry if I don't post all the code but there are a lot of sensitive data and is very long. Can anyone help me?

It's possible that what gets output as far as from a generation standpoint might be outputting a different name, which is a challenge with ASP.NET (since you have no control). If your JS code is defined within the ASPX, you can guarantee a match by use the <%= %> notation with a combination of the UniqueID of the control, as the following:
rules: {
<%= Nome.UniqueID %>: {
required: true,
minlength: 2
},
<%= Email.UniqueID %>: {
required: true,
email: true
},
...
The syntax
<%= Email.UniqueID %>
outputs a matching generated name, which may be a part of the problem. It may say (in visual studio) that there is a formatting error in the JS, but this shouldn't have any problem on execution since it will guarantee a matching name.

Related

jQuery Validation for Input Type File

I am using jQuery validation on my form with couple of textboxes, drop down lists and a file input. I've also added additional_methods.js for extension method. It works perfectly, except for file input. It shows default error message for required not custom message, and extension part is not working neither.
Html:
<input type="file" id="Logo" class="form-input-styled" required>
jQuery:
$('.form-validate').validate({
ignore: 'input[type=hidden], .select2-search__field',
errorClass: 'validation-invalid-label',
successClass: 'validation-valid-label',
validClass: 'validation-valid-label',
highlight: function (element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function (element, errorClass) {
$(element).removeClass(errorClass);
},
success: function (label) {
label.addClass('validation-valid-label').text('Başarılı.');
},
errorPlacement: function (error, element) {
if (element.parents().hasClass('form-check')) {
error.appendTo(element.parents('.form-check').parent());
}
else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo(element.parent());
}
else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) {
error.appendTo(element.parent().parent());
}
else {
error.insertAfter(element);
}
},
rules: {
Logo: {
required: true,
extension: "png"
}
},
messages: {
Logo: {
required: "Please select a business logo!",
extension: "Please select a valid logo!"
}
}
});
Problem solved! When I add name property to the input, it works perfectly as i wanted. Custom error message is working now.
<input type="file" id="Logo" name="Logo" class="form-input-styled" required>

how to add NOTEqual To rule in jQuery.validation

I want to know how i can add jquery validation for not equal values in two input textbox. I have tried this Example but its not working for me.
Jquery Code:
$.validator.addMethod("notEqual", function (value, element, param) {
return this.optional(element) || value != param;
}, "cannot be same as oldpassword");
$("#frmAddEdit").validate({
rules: {
"txtoldpassword": { required: true },
"txtnpassword": { required: true, notEqual:"#txtoldpassword" },
},
messages: {
"txtoldpassword": { required: "old Password is required" },
"txtnpassword": { required: "New Password is required" },
},
submitHandler: function (form) {
ChangeUserPassword();
return false;
}
});
When i put alert on validation method param shows the same value (i.e. #txtoldpassword) and when i put like this notEqual: $("#txtoldpassword").val() param becomes ""(blank)
Please help me on this.
I just changed the way of passing value of textbox for notEqual and it worked for me.
JQuery Code :
$("#frmAddEdit").validate({
rules: {
"txtoldpassword": { required: true, noSpace: true },
"txtnpassword": {
required: true, noSpace: true, notEqual: function () { return $("#txtoldpassword").val() },
}
},
messages: {
"txtoldpassword": { required: "old Password is required" },
"txtnpassword": { required: "New Password is required" },
},
submitHandler: function (form) {
ChangeUserPassword();
return false;
}
});

Razor asp.net: access javascript variable

Currently I have this:
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: {
transport: {
read: {
url: "#Html.Raw(
Url.Action(
"Filter_Rooms",
"Room",
new {
pFilter = false,
pCapacity = 25,
pBeamer = true,
pTelevision = false
}))",
dataType: "json"
},
}
}
}
]
These parameters pFilter = false, pCapacity = 25, pBeamer = true, pTelevision = false, for the filter are now hard coded but actually I want them from:
HTML
<div class="checkbox">
<label>
<input id="chkBeamer" type="checkbox"> Beamer available
</label>
</div>
Filter rooms
Javascript
$(document).ready(function () {
$("#btnFilter").click(function () {
var pFilter = document.getElementById("chkBeamer").checked;
});
});
Can I get the javascript to use the pFilter parameter instead of the hard-coded ones?
HTMLHidden
<div class="checkbox">
<label>
#Html.Hidden("pBeamer", true);
<input id="chkBeamer" type="checkbox"> Beamer available
</label>
</div>
Javascript Resources
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: {
transport: {
read: {
url: "#Html.Raw(
Url.Action(
"Filter_Rooms",
"Room",
new {
pBeamer = ("#pBeamer")???
}))",
dataType: "json"
},
}
}
}
]
There are two ways in which you can do this:-
1) You can have hidden fields for each of these four fields which you can fill in your Javascript function on click of btnFilter. Access those hidden fields while using resources.
#Html.Hidden("pFilter","<value>");
You can access these hidden fields in your code below.
resources: [
{
field: "roomId",
name: "Rooms",
dataSource: {
transport: {
read: {
url: "#Html.Raw(
Url.Action(
"Filter_Rooms",
"Room",
new {
pFilter = <get value from hidden field>,
pCapacity = <get value from hidden field>,
pBeamer = <get value from hidden field>,
pTelevision = <get value from hidden field>
}))",
dataType: "json"
},
}
}
}
]
2) You can have global variables to which you assign values on btnFilter click and use it in resources as you are doing currently.
I would suggest you to follow the first solution.

Uncaught TypeError: undefined is not a function - Highcharts - MVC

I'm trying to use Highcharts in my MVC web application. I have loaded all the prerequisites to make Highcharts working. But apparently, "highchart" is still not recognized by the page. I'm checking the rendered page by google developer tool and it says all the JQuery and Highchart javascript files are loaded properly. Any help?
This is my .cshtml code:
#using System.Web.Optimization
<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/Highcharts-4.0.1/js/highcharts.js")
#Scripts.Render("~/Scripts/Highcharts-4.0.1/js/modules/exporting.js")
<script type="text/javascript">
$(function() {
var chart;
debugger;
$(document).ready(function() {
debugger;
// Build the chart
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2014'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}]
});
});
});
</script>
}
So this does the trick (which is kind of weird!) :
I need to change this line:
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
To this line:
chart = new Highcharts.Chart({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
renderTo: 'container'
},
This is the link which helped me through: http://developmentpassion.blogspot.com/2013/09/bar-charts-and-graphs-in-aspnet-mvc.html

jQuery validate not working with jQuery multiselect

I am using the jQuery validator to validate a jQuery multiselect dropdownlist but it does not validate, my functions are bellow:
These functions are created from my code behind and registered on the page with the ScriptManager.RegisterClientScriptBlock.
I put the following directly on the aspx page and it then validates the multiselect, but as soon as I do it from the code behind and register the script, all validators besides the multiselect works.
$.validator.addMethod('notNone', function(value, element) {
return (value != '-1');
}, 'Please select an option.');
var $callback = $("#callback");
$(document).ready(function () {
$("#<%=example.ClientID%>").multiselect(
{
show: "fade",
hide: "fade",
click: function (event, ui) {
$callback.text(ui.text + ' ' + (ui.checked ? 'checked' : 'unchecked'));
},
});
});
$("#form1").validate({
rules: {
<%=example.UniqueID %>: {
notNone: true,
},
<%=txtPassword.UniqueID %>: {
//minlength: 5,
//required: true
},
<%=TextIdea.UniqueID %>: {
//minlength: 5,
//required: true
},
<%=ddlTest.UniqueID %>: {
//notNone: true
},
redemption : {
redemption : false
},
redemption: {
redemptionEnd : false
},
},
ignore: ':hidden:not("#<%=example.ClientID %>")',
messages: {
<%=example.UniqueID %>:{
notNone: "Plaese select something",
},
<%=txtPassword.UniqueID %>:{
required: "Plaese enter your password",
minlength: "Password must be atleaet of 5 characters"
},
<%=TextIdea.UniqueID %>:{
required: "Plaese enter your Ideas",
minlength: "Password must be atleaet of 5 characters"
},
}
});
My markup:
<select id="example" name="example" runat="server">
</select>
Am I doing something wrong? Please help guys.
Thanks in advance.
Okay, after 2 days I finally figured out what was going on, turns out the controls that use the jQuery multiSelect, their UniqueID gets appended with _multiSelect and the ClientID gets appended with $multiSelect.
Added those strings when getting the Client/UniqueID and it works.

Categories