0

So I havent done any ASP.net for awhile, and im trying to call some javascript validation, which works, then I need to call a Code behind event.

I thought it was going to be easy, but its turned into a right nuisance.

All i want to do is check if the text box is empty, if so thow an alert and dont run any service side methods, if its not not empty then run method.

dont mind changing the code, (although have to keep using materpages and content sections).

 <input type="submit" value="Update" onclick="validate()"/>
<SCRIPT LANGAUGE="JavaScript">
       function validate() {

           var jname = document.getElementById('MainContent_txtname').value;

           if (jname == null) {
               alert("Please Enter Name");

           }
           else {
               CallServerMethod();
           }
        }
       function CallServerMethod() {

                UpdateClient() //I dont work
                }
       </SCRIPT>

any ideas? Thanks

D-W
  • 5,201
  • 14
  • 47
  • 74

6 Answers6

2

You can make Ajax to make a call to a server page ( an aspx page/ .ashx handler) to do this. This is how you will do it with jQuery (if you are already using that in your project)

function CallServerMethod()
{
    $.post("yourserverpage.aspx", { name : "Scott" }, function(data){
      //now data variable has the result from server page. do whatver you 
      // want with that. May be an alert
     alert(data);
    });
}

In your yourserverpage.aspx file, you can read the name key value from the request parameter and do whatver server code you want to execute and return something back with a Response.Write() method

Ex : Response.Write("user saved");

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Good Call, but a right pain ive got to use (MUST) use Javascript, i know i would of used jquery myself – D-W May 23 '12 at 17:11
  • @D-W : You can do the same thing with pure javascript. Take a look at Max's answer. jQuery is simply( **but awesome**) library which has this code already. so we are doing a shorthand by using jQuery library. Behind the scene it is the same javascript being executed. – Shyju May 23 '12 at 17:14
  • jquery is just a javascript library. Are you saying you're not allowed to use 3rd party libraries? – Simon Halsey May 23 '12 at 18:01
0

There is an abundance of information on this topic on this site.

Here's a good start for you: Call server side function from client side javascript

Community
  • 1
  • 1
Jeremy
  • 8,902
  • 2
  • 36
  • 44
0

What you are looking for is ajax. The easier way is to use jquery which has a $.get or $.getJSON or $.ajax method that wraps the xmlhttprequest ( object used to call server method from javascript ).

Another easy way would be to look into WebMethod. You need to set [WebMethod] attribute to your server side method, add a script manager to your aspx page and then call the server method with PageMethods.MyServerMethod

$.ajax({
    type: "POST",
    url: "mypage.aspx/ServerMethodName",    
    data: '{"id":"' + $("#divID").text() + '"}',        
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (returnValueFromServerMethod) {
        if(returnValueFromServerMethod.d != "")
            //do something great

    }
});

[WebMethod]
public static string ServerMethodName(string id)
{
    HttpContext.Current.Session["ID"] = id;            
}

You will need to add a a script manager in your page.aspx to enable page methods.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">                    
</asp:ScriptManager>

You can replace the page method stuff with a service .svc which would be cleaner.

Dave
  • 2,774
  • 4
  • 36
  • 52
0
function validate(){
    var jname = document.getElementById("MainContent_txtname').value;

    if(jname.length == 0){
        alert("Empty text field");
    }else{
        CallServerMethod(jname);
    }
}
function CallServerMethod(param){
    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //we have an xmlhttp object
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            var response = xmlhttp.responseText;
            UpdateClient(response);         
        }
    }
    xmlhttp.open("GET","server_page.php?jname="+param,true);
    xmlhttp.send();
}
function UpdateClient(response){
    alert("Server responded with response: "+response);
}

Then set validate to the onChange event. So....<input....onChange="validate();" />

Obviously server_page.php could also be server_page.asp or anything else, the parameter is simply URL encoded in the GET request. You could also send it using a post request, but this requires some more work...

//in the last part of CallServerMethod(),
//replace the last 2 lines with:
xmlhttp.open("POST","server_page.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length",param.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(param);
Max Snijders
  • 374
  • 2
  • 10
  • BTW: this is **without** JQuery, which I personally prefer, because of higher predictability and slightly higher speed, although this difference is very marginal. I just like to see the code so that I can learn about how the system actually works, so I know that, instead of just knowing how to build a website (about as quickly) without knowing what's going on on my own site. – Max Snijders May 23 '12 at 17:13
  • oops...I just saw... So stupid of me. In line 1 of the function contents the " and ' don't match up. Should you use this code, you'll have to change that... – Max Snijders May 23 '12 at 17:22
0

I've been using the .ajax({ ... way to do this. However, I recently came across an alternative and easier way to achieve this - MSDN link

neuDev33
  • 1,573
  • 7
  • 41
  • 54
0

A simple solution would be to have your javascript click a hidden button.

<SCRIPT LANGAUGE="JavaScript">
   function validate() {

       var jname = document.getElementById('MainContent_txtname').value;

       if (jname == null) {
           alert("Please Enter Name");

       }
       else {
           CallServerMethod();
       }
    }
   function CallServerMethod() {

            document.getElementById('<%#btnRefresh.ClientID %>').click(); 
            }
   </SCRIPT>

Then in your button click event in the codebehind do whatever you wanted it to do.

If I understood you right this seems like the simplest solution.

Cruril
  • 450
  • 4
  • 14