How to call C# Method from Java Script

How to call C# Method from Java Script

If you want to call any method of cs page from JS then this is the best way that you can follow.
This is required when ur buttons onClick event are not fired den u can call the onClientClick of button and then call the required method.

Step 1:

Create any page lets say Default.aspx.

<script type=”text/javascript”>
function Signup() {
var name = document.getElementById(“txtName”).value;

PageMethods.Sendmail(name, onSucess, onError);

function onSucess(result) {
document.getElementById(“successMessage”).innerHTML = result.toString();
}

function onError(result) {
document.getElementById(“successMessage”).innerHTML = “Cannot process your request at the moment, please try later.”;
}
}
</script>

With in the body part look carefully

<body>
<asp:ScriptManager ID=”smContent” runat=”server” EnablePageMethods=”true”>
</asp:ScriptManager>
<div>
Name:   <input type=”text” id=”txtName” />
<asp:LinkButton ID=”btnSubmit” runat=”server” Text=”Signup” OnClientClick=”Signup();   return  false;”></asp:LinkButton>
</div>
<div id=”successMessage”></div>
</body>

Step 2:

In the cs page just write the below code.
[WebMethod]
public static string Sendmail(string name)
{
string result = “Congratulations!!! your email has been sent.”;
if (name.Length == 0)//Zero length check
{
result = “name cannot be blank”;
}
else
{
result = “Record Verifed.”;
}
return result;
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply