簡體   English   中英

從html頁面調用ac#類方法

[英]calling a c# class method from html page

我們可以從html頁面的類中調用C#方法嗎? 我有一個班級名稱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();
        }

    }
}

我想從html頁面調用此方法。我使用的是html頁面而不是asp頁面。是否有可能在不使用ajax的情況下進行調用,或者如果ajax也應該如何調用。

    <!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>

這是我的代碼。 在這里,我無法在crud類中調用generateFiles()方法。 我可以打電話給我嗎?

您不能調用普通方法。 該方法必須是靜態方法和Web方法。

嘗試這個:

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

    }
}

基本語法

<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"
}

如果要使用不帶ajax的頁面調用: 參考

//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>

您在項目中缺少控制者。

您嘗試從沒有控件(或[WebMethod])的cs文件中檢索數據嗎? 這是不可能的。

嘗試尋找一些MVC指南,這是來自Microsoft網站的指南

您不必使用那里顯示的所有ASP組件,但是可以在那里看到如何從服務器到客戶端檢索數據。

如果使用的是ASP.NET Web窗體,則可以使用WebMethodAttribute來代替直接調用.cs文件的方法,該文件不受AJAX支持,因為沒有為常規類啟用URL路由。 該web方法必須聲明為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();
        }
    }
}

然后,應將您的AJAX調用URL更改為此(請注意,Web方法應該存在於代碼隱藏文件中,例如Crud.aspx.csCrud.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.");
          }
});

如果使用ASP.NET MVC,請使用JsonResult返回JSON字符串作為success結果:

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

對action方法的AJAX調用看起來相似,但URL部分略有不同:

$.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.");
          }
});
    //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 ");
        }
    });

//請在您的方法上提及[WebMethod]屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM