1

Can we call a C# method in a class from a html page?? I have a class names Crud.cs

public class Crud
{
    public String generateFiles(String name)
    {

        return(generateHtml(name));
    }
     private String generateHtml(String name)
    {

       var filename = "C:\temp\"" + name + ".html";

        try
        {
            FileStream fs = new FileStream(filename, FileMode.Create);
            return "True";
        }
        catch(Exception e)
        {
            return e.ToString();
        }

    }
}

I want to call this method from a html page.I'm using a html page not a asp page.Is there any possibility to call without using ajax or if ajax also how could I call.

    <!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="http://ajax.microsoft.com/ajax/jQuery/jquery-3.2.1.js" type="text/javascript"></script>     

</head>
<body>
    <div style="align-content:center;">
        <input type="text" id="HtmlName" />
        <button id="btn_gen_html" onclick="createHtml()">Generate</button>
    </div>
    <div id="Msg"></div> 
    <div id="feedbackMsg"></div> 
    <script>
        function createHtml() {
            var name = document.getElementById("HtmlName").value;

            $.ajax({
                type: "POST",
                url: "Crud.cs/generateFiles",
                data: { name } ,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (val) {
                    alert(val);

                    if (val == 0) {
                        $("#feedbackMsg").html("Success");
                    }
                    else(val==1)
                    {
                        $("#feedbackMsg").html("Sorry cannot perform such operation");
                    }
                },
                error: function (e) {
                    $("#feedbackMsg").html("Something Wrong.");
                }
            });
        }
    </script>
</body>
</html>

This is my code. Here I am not able to call generateFiles() method in crud class. Can I call so.And if I can How?

6
  • 1
    Short answer: you can't. Crud.cs/generateFiles is an invalid URL in AJAX call (since .cs files are compiled & you need to return HTML/JSON), even C# code doesn't reached. If you're using ASP.NET MVC, the URL assigned with controller & action method name (set the action method to return JSON result). Commented Sep 6, 2017 at 5:48
  • Hi @TetsuyaYamamoto Thanks for fast reply.. But I didn't get what u telling. Can u please explain in brief Commented Sep 6, 2017 at 5:51
  • Try something like this ProjectName.namespace.c#function. you can't call .cs file like that Commented Sep 6, 2017 at 5:52
  • @MeghaM use change the method to static and put [WebMethod]. Commented Sep 6, 2017 at 5:54
  • The AJAX call URL requires valid routing to interact with C# code, so that you can't use .cs files directly. In ASP.NET MVC the URL routing is enabled, so that you can use controller class name & action method name to refer in URL. However with setup you have above without any URL routing, the AJAX doesn't know which route should be taken to call backend C# code. Commented Sep 6, 2017 at 5:55

5 Answers 5

0

You can't call normal method. The method must be static and web method.

Try this:

public class Crud
{
    [WebMethod]
    public static String generateFiles(String name)
    {

        return(generateHtml(name));
    }
     private String generateHtml(String name)
    {

       var filename = "C:\temp\"" + name + ".html";

        try
        {
            FileStream fs = new FileStream(filename, FileMode.Create);
            return "True";
        }
        catch(Exception e)
        {
            return e.ToString();
        }

    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are missing a controler in your project.

You try to retrieve data from a cs file without a controler (or a [WebMethod])? this is impossible.

Try looking for some MVC guides, Here is one from microsoft web site

You dont have to use all that ASP component that showen there, but you can see there how to retrieve data from the server to the client.

Comments

0

Basic syntax

<script type="text/javascript">             //Default.aspx
   function myfunction() {     
             $.ajax({
             type: "POST",
             url: 'Default.aspx/myfunction',
             data: "mystring",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             success: function (msg) {
                 alert("success");
             },
             error: function (e) {
                 $("#divResult").html("Something Wrong.");
             }
         });
     }

Default.aspx.cs

[WebMethod]
public static String myfunction(string name)
{
    return "Your String"
}

If you want to use page call without ajax: Ref

//cs file (code behind)
[ScriptMethod, WebMethod]
public static string GetLabelText(string param1)
{
   return "Hello";
}
//aspx page
 <script type="text/javascript">
  function InsertLabelData() {
      PageMethods.GetLabelText(param1,onSuccess, onFailure);
  }

  function onSuccess(result) {
      var lbl = document.getElementById(‘lbl’);
      lbl.innerHTML = result;
  }

  function onFailure(error) {
      alert(error);
  }
  InsertLabelData();
</script>

2 Comments

How to send parameters in second method PageMethods.GetLabelText(onSuccess, onFailure);
@MeghaM have you tested?
0

If you're using ASP.NET Web Forms, there is a WebMethodAttribute you can use instead of calling .cs file directly which unsupported by AJAX due to no URL routing enabled for normal classes. The web method must be declared as static:

// if you're using ASMX web service, change to this class declaration:
// public class Crud : System.Web.Services.WebService
public class Crud : System.Web.UI.Page
{

    [System.Web.Services.WebMethod]
    public static String generateFiles(String name)
    {
        return generateHtml(name);
    }

    private String generateHtml(String name)
    {
        var filename = "C:\temp\"" + name + ".html";

        try
        {
            FileStream fs = new FileStream(filename, FileMode.Create);
            return "True";
        }
        catch(Exception e)
        {
            return e.ToString();
        }
    }
}

Then your AJAX call URL should be changed to this (note that the web method should be exist in code-behind file, e.g. Crud.aspx.cs or Crud.asmx.cs):

$.ajax({
          type: "POST",
          url: "Crud.aspx/generateFiles", // web service uses .asmx instead of .aspx
          data: { name: name }, // use JSON.stringify if you're not sure
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (val) {
             alert(val);
             if (val == 0) {
                $("#feedbackMsg").html("Success");
             }
             else
             {
                 $("#feedbackMsg").html("Sorry cannot perform such operation");
             }
          },
          error: function (e) {
             $("#feedbackMsg").html("Something Wrong.");
          }
});

If ASP.NET MVC is used, use JsonResult to return JSON string as success result:

public class CrudController : Controller
{
    [HttpPost]
    public JsonResult generateFiles(String name)
    {
        return Json(generateHtml(name));
    }
}

The AJAX call for the action method looks similar but the URL part is slightly different:

$.ajax({
          type: "POST",
          url: "Crud/generateFiles",
          data: { name: name }, // use JSON.stringify if you're not sure
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (val) {
             alert(val);
             if (val == 0) {
                $("#feedbackMsg").html("Success");
             }
             else
             {
                 $("#feedbackMsg").html("Sorry cannot perform such operation");
             }
          },
          error: function (e) {
             $("#feedbackMsg").html("Something Wrong.");
          }
});

4 Comments

But I'm using just a class not .aspx.cs file ..So how can I give it in url..My file name is Crud.cs..How can I use it in url
To use WebMethod, the method should placed in a class that derives System.Web.UI. So that you can create Crud.aspx page & Crud.aspx.cs code behind, then you can use web method inside public class Crud : System.Web.UI.Page. If you're taking MVC route, just adding Controller to make it controller class & decorate action method with HttpPost.
But I'm not using .aspx page..I'm just using .html page I'm not using MVC, I'm using webforms
You can call the C# code from web method URL with just HTML & JS, but the C# code takes place inside code-behind file, either in ASPX or ASMX web service (.asmx.cs) code which has WebMethod (public class Crud : WebService).
0
    //Perfect solution
  var params = { param1: value, param2: value2}
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '../aspxPage.aspx/methodName',
        data: JSON.stringify(params),
        datatype: 'json',
        success: function (data) {
       var  MethodReturnValue = data.d

        },
        error: function (xmlhttprequest, textstatus, errorthrown) {
            alert(" conection to the server failed ");
        }
    });

//PLEASE menntion [WebMethod] attribute on your method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.