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?

Megha M
  • 105
  • 1
  • 10
  • 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). – Tetsuya Yamamoto Sep 06 '17 at 05:48
  • Hi @TetsuyaYamamoto Thanks for fast reply.. But I didn't get what u telling. Can u please explain in brief – Megha M Sep 06 '17 at 05:51
  • Try something like this ProjectName.namespace.c#function. you can't call .cs file like that – Znaneswar Sep 06 '17 at 05:52
  • @MeghaM use change the method to static and put [WebMethod]. – Sarath Kumar Sep 06 '17 at 05: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. – Tetsuya Yamamoto Sep 06 '17 at 05:55
  • You can refer to this link - https://stackoverflow.com/questions/18441194/how-to-call-a-c-sharp-function-from-javascript – Phani Kumar M Sep 06 '17 at 05:57

5 Answers5

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();
        }

    }
}
Sarath Kumar
  • 1,136
  • 1
  • 18
  • 41
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>
Znaneswar
  • 3,329
  • 2
  • 16
  • 24
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.

roee58
  • 11
  • 3
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.");
          }
});
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • 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 – Megha M Sep 06 '17 at 06:24
  • 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`. – Tetsuya Yamamoto Sep 06 '17 at 06:28
  • But I'm not using .aspx page..I'm just using .html page I'm not using MVC, I'm using webforms – Megha M Sep 06 '17 at 06:37
  • 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`). – Tetsuya Yamamoto Sep 06 '17 at 06:42
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.

Nitin Ware
  • 109
  • 9