I have a ListView whose template has a LinkButton with a CustomValidator.
<ItemTemplate>
<div>
<asp:LinkButton runat="server" ID="_linkButtonDelete"
ValidationGroup='<%# DataBinder.Eval(Container.DataItem. "Id") %>'
CausesValidation="true" />
<asp:CustomValidator runat="server" ClientValidationFunction="validateDelete"
ValidationGroup='<%# DataBinder.Eval(Container.DataItem. "Id") %>'
data-itemId='<%# DataBinder.Eval(Container.DataItem. "Id") %>'>*</asp:CustomValidator>
</div>
</ItemTemplate>
In validateDelete function I perform a synchronous AJAX request to determine whether the specific item can be deleted.
function validateDelete(sender, args){
var itemId = sender.dataset.itemid;
$.ajax({
async:false
// other settings omitted
success: function(jsonResult){
args.IsValid = jsonResult.CanDelete;
}
});
}
However, when I click on a button for which validateDelete function sets args.IsValid = true (I checked the response with Fiddler and by debugging the function) the link does not trigger a postback and the validator is invalid (i.e. I can see the red * near the button).
Why does the validator remain invalid?
i implement your scenario, and cause i do not know your code behind, i sent my request to a ashx handler :
$.ajax({
async: false,
url: "Handler1.ashx",
success: function (jsonResult) {
args.IsValid = jsonResult == "False" ? false : true;
}
});
and this is handler1.ashx implementation :
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(true); // this return value was changing manually
// to test both true and false situations
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
everything work fine, probably the problem is where you assign args.IsValid, try to cast jsonResult.CanDelete if its not boolean before set args.IsValid, like something i have done using iif, may your problem be solved...
i do not know, whether this javascript codes you copy here is differ with its original on your page... but after async:false u need a ,
Thanks to hints from #Șhȇkhaṝ and #am1r_5h and the suggests from here, namely
setting args.IsValid at the end of the code
I was able to perform validation on client by refactoring the validateDelete function into this:
function validateDelete(sender, args){
var itemId = sender.dataset.itemid;
var isValid; // <- declare outer scope variable to hold the result
$.ajax({
async:false
// other settings omitted
success: function(jsonResult){
isValid = jsonResult.CanDelete; // <- set the result of ajax call
}
// Set args.IsValid at the end of the function.
args.IsValid = isValid;
});
}
Related
I have a handler StackOverFlow.cs like below:
public class StackOverFlow: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var nameValueCollection = HttpUtility.ParseQueryString(HttpUtility.UrlDecode(encodedUrl));
//..
}
}
I get QueryString parameters with ParseQueryString.
How can I test it with jquery post? Is it possible?
For example below code use a URL which ends .ashx, is it possible to use with .cs?
How can I trigger my StackOverFlow class which inherits IHttpHandler with html POST?
<script type="text/javascript">
$(function () {
//we bind the submit click function
$("#btnSubmitJSON").click(function(){
var nameValue = $("#txtName").val();
var emailValue = $("#txtEmail").val();
var contactValue = $("#txtContactNo").val();
//we just use a quick check if the value are empty or not
if(nameValue != "" && emailValue != "" && contactValue != ""){
//we can hide the button just to make sure user does not click the button during the progress.
$("#btnSubmitJSON").show();
//we can output ajax icon loading so the user know it is in progress.
$("#output").html("<img src=\"/content/images/ajax-loader.gif\" /> Please wait, we are processing your request.");
//we build the json string
var jsonData = {
'Name': nameValue,
'Email': emailValue,
'Contact': contactValue
}
//note in order to proper pass a json string, you have to use function JSON.stringfy
jsonData = JSON.stringify(jsonData);
$.ajax({
url: "/ContactHandler.ashx", //make sure the path is correct
cache: false,
type: 'POST',
data: jsonData,
success: function (response) {
//output the response from server
$("#output").html(response);
//we clean up the data
$("#txtName").val("");
$("#txtEmail").val("");
$("#txtContactNo").val("");
},
error: function (xhr, ajaxOptions, thrownError) {
$("#output").html(xhr.responseText);
$("#btnSubmitJSON").show();
}
})
}else{
$("#output").html("Please enter all fields.");
}
});
});
</script>
you need a collection of tests, an end to end test , an unit test for the javascript stubbed against a fake backend service and a unit test for the your handler, i can't give example but that is what is needed, there are lots of resources out there for unit testing C# code , javascript code and system end to end tests
I am creating registration page and doing null field validation on submit button click using jquery. if there is any error in form validation then i am preventing default method call using jquery, so it will not call code behind button click event.
Problem:
sometimes user double clicked on button and this is calling code behind button click event two times with two database row insertion having a same data.
I tried lots of solution but unfortunately i couldn't make any success.
Please help me to solve out this problem if you have any solution.
Thanks in advance,
Actually, i was preventing default server side method call in jquery when button is clicked using e.PreventDefault() method of jquery if validation is false.
Don't know what was the problem but when i set function on client click of button and return true/false based on validation instead of e.PreventDefault, trick worked great for me.
Thanks to all who comment on this question.
Simply add a variable called 'loading' for example and check if the ajax call is busy:
At the top of your code:
var loading = false;
Then on form submit:
$('#form').submit() {
if(loading)
return false;
loading = true;
//Ajax call
$.ajax({
type: "POST",
url: "somePage.php",
data: $('#form').serialize(),
success: function(response) {
loading = false;
//Your response code
}
});
}
Use one on the client side. This will prevent double clicks.
$("#button").one("click", function() {
// validate the form.
// if form is valid, submit form
});
An alternative solution is to have a boolean flag.
var submitting = false;
$("#button").click(function() {
if (!submitting) {
submitting = true;
if (formIsValid) {
submitting = false;
$("#form").submit();
} else {
submitting = false;
}
}
});
Add disabled attribute to your button as the first thing in your js method.
function func(event) {
$("#button").prop("disabled", true);
.....
}
try this it might help for your asp button
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" UseSubmitBehavior="false" OnClientClick="ValidationCode(event); return false;" />
<script>
function ValidationCode()
{
//Code of validtion
event.preventDefault();
if(true)
{
__dopostback:("btnSubmit","");
}
}
</script>
Sample code
Client Side:
$("#submit").click(function () {
if (!YourvalidationFunction)
{
return false;
}
else {
//ajax_function is a folder contain Default.asmx page and insertNewRecord is function name (server side)
$.ajax({
type: "POST",
url: "ajax_function/Default.asmx/insertNewRecord",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessinsertingwcCall,
error: OnErrorCall
});
}
});
Server Side:
[WebMethod]
public string[] insertNewRecord(string prefix)
{
string status = "";
List<string> d = new List<string>();
try
{
// logic code for insertion if success set msg
status = "New record inserted";
}
catch (Exception ac)
{
status = " Error occurs";
}
d.Add(string.Format("{0}", status));
return d.ToArray();
}
Using jquery 1.7.2 and .net 4.0
I have a json ajax call that sets the value of a asp hidden field on my form. While stepping through the code behind I can see the value the hidden field is set but when the code returns to the aspx code the value is empty.
ASPX code:
<asp:HiddenField ID="hidden1" runat="server" />
//dropdownlist on change event calls the function below:
function getReport() {
var data = { MethodName: 'myMethod', value1: value1 }
var options = {
url: '<%=ResolveUrl("myPage.aspx") %>',
async: false,
data: data,
datatype: 'text',
type: 'POST',
success: function () {
var returnedData = $("#hidden1").val();
alert('returned data = ' + returnedData);
}
}
$.ajax(options);
//also tried alerting the returned data here.. still empty
}
c# code behind:
#region AJAX
if (Request.Form["MethodName"] == "myMethod")
{
hidden1.Value = "please just pass this value!!!";
return;
}
else
{
//do something different.
}
#endregion
I've simplified my code, hopefully not too much. and I double checked my code to make sure the hidden field value is not set elsewhere in the code.
Due to the ajax call the the hidden field will not be updated. You must use the data which is returned by the ajax call.
function getReport() {
var data = { MethodName: 'myMethod', value1: value1 }
var options = {
url: '<%=ResolveUrl("myPage.aspx") %>',
async: false,
data: data,
datatype: 'text',
type: 'POST',
success: function (returnedData) {
alert('returned data = ' + returnedData);
}
}
$.ajax(options);
}
code behind:
#region AJAX
if (Request.Form["MethodName"] == "myMethod")
{
return "please just pass this value!!!";
}
else
{
//do something different.
}
#endregion
I call another page with an id, which returns the data based on id. I need the result value in JavaScript.
Then I need to bind the result to current page content area and display it to the user.
Initially, the user clicks one link in current page, then the id of the link should be passed to another page, and processed some function and get result from db.
I want to display the result in current page.
I am using vs2010. How can I do this?
So, you already have solved your asp.net part (you have the page, right?).
What you can do is use jquery and make an ajax call to that page and process the result. If your page returns a the information in json or xml format, it's easy to use it to upgrade your current document in the browser.
Here you will find the documentation and some samples of Jquery ajax: http://api.jquery.com/jQuery.ajax/
Hope it helps.
function ajaxCall(id_from_your_page){
$.ajax({
type: "POST",
url: '/service.asmx/your_method',
data: { 'id', id_from_your_page },
dataType: "application/json; charset=utf-8",
success: function(result){
alert("i got your result: " + result);
}
});
}
the above code is better as you will use JQuery and POST method.
you may also like this-
function sendRequest(id) {
var xmlObj = null;
if(window.ActiveXObject) {
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlObj = new XMLHttpRequest();
}
if(!xmlObj) return;
var location = "http://localhost:8080/myapplication/mypage?id="+ id;
xmlObj.open("GET", location, true);
xmlObj.onreadystatechange = function() {
if(xmlObj.readyState==4 && xmlObj.status==200) {
doSomethingWithTheResponse(xmlObj.responseText);
}
}
xmlObj.send(null);
}
function doSomethingWithTheResponse(responseText) {
// write your own code to handle the response from the page.
}
All the best :)
You can get the Id/Data from other pages or Db like this....
<asp:LinkButton runat="server" Text='<%#Eval("Title")%>'OnClick='javascript:ShowEventDetails'CommandArgument='<%#Eval("EventID").ToString()%>);'/>
or
onclick='<%# "PopulateTicketDiv(" +Eval("SHOW_ID") + " );" %>'
ASPX:
<asp:Button ID="btnget" runat="server" Text="Create WR" onClientClick="<%# GetPopupScript() %>" />
Code-behind:
protected string GetPopupScript() {
return string.Format( "javascript:popUp('popup_createWR.aspx', '{0}', '{1}')", Eval( "dvc_nm" ), Eval( "data_orgtn_yr" ) ); }
or try this...
<asp:LinkButton ID="LinkButton5" OnClientClick='<%# "return fun1(""" + Eval("mid") + """);"%>' runat="server"><%#Eval("mname")%></asp:LinkButton>
I have an ASP.NET ImageButton that OnClientClick() is supposed to fire a js function that reads the values from a two text fields, send it to a server-side WebMethod. With the WebMethod sending it to another entity method which handles the storage. I've tried debugging by setting breakpoints in the WebMethod and storage method on the serverside but neither is getting reached. I then tried setting a breakpoint on client-side using the Mozilla Firebug tool. The js function never gets called and the page just refreshes. I set a breakpoint in another js function and it was traced perfectly. Any help?
ASP
<asp:ImageButton input="image" ID="btnSend" ImageUrl="Images/send_button.jpg"
runat="server"
onclientclick="javascript:handle(); return false">
</asp:ImageButton>
JS
function handle() {
window.$get("#" + "<%= btnSend.ClientID %>").click(
function () {
var txtVC = window.$get("#" + "<%= txtVC.ClientID %>").value();
var txtMsg = window.$get("#" + "<%= tbMgSend.ClientID %>").value();
if (txtVC != "" || txtMsg != "") {
window.PageMethods.SendMsg(txtVC, txtMsg, txtMessageResult);
return window.$get("#" + "<%= lblMessageStatus.ClientID%>").value("SUCCESS"),
alert("SUCCESS");
}
else {
return alert("Text Message is Empty!");
}
});
}
function txtMsgResult(result) {
if (result != '') {
window.$("#" + "<%= lblMessageStatus.ClientID %>").innerHTML = result;
alert("SUCCESS");
}
}
I've tried the following:
* OnclientClick with and without return
* $get with and without concat(+)
* changing the server-side to a method instead of web method and that also didn't fire
Have you tried it without the return false?
<asp:ImageButton input="image" ID="btnSend" ImageUrl="Images/send_button.jpg"
runat="server"
onclientclick="handle()">
</asp:ImageButton>
Maybe it doesn't work because it autoPostBack.
I'm not sure there is a way to turn it off in an ImageButton. Why not use a HTML control instead ?