【问题标题】:Invoking Controller method from Html page从 Html 页面调用控制器方法
【发布时间】:2014-09-09 11:12:39
【问题描述】:

我创建了一个 HTML 页面,比如 SomePage.Html,我希望每当我访问这个页面时,都应该调用一个方法。

假设我创建了一个控制器 DefautController 并且它有一个名为 - Get() 的方法,那么每当我访问“../SomePage.Html”时,应该引发这个“Get()”。

SomePage.Html :-

<!DOCTYPE html>
<html>
<head>

    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
        function codeAddress() {

            alert('ok');
        }

    </script>
</head>
<body onload="codeAddress();">

</body>
</html>

默认控制器:-

public class DefaultController : Controller
{
    // GET: Default
    public ActionResult Index()
    {
        return View();
    }


    [System.Web.Http.HttpGet]
    public IHttpActionResult Get()
    {
    }
}

我该怎么做。我对此非常天真 - WebApi/Asp.net 的事情。谢谢:)

【问题讨论】:

  • 您应该使用PageMethodsAjax Get/Post 调用,您可以从html 页面调用方法背后的代码。

标签: c# html asp.net .net asp.net-web-api


【解决方案1】:

你可以使用 jQuery

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

    $.ajax({
        type: 'GET',
        url: '/Default/index',
        data: { },
        cache: false,
        success: function(result) {
                 alert(result);

        }
    });

</script>

【讨论】:

  • 方法没有被调用:(当我加载页面时
【解决方案2】:

您必须在 URL 中提供方法名称 Get 而不是 index 方法

 $.ajax({
                            url: '@Url.Action("Get", "Default")',
                            data: {},
                            type: 'GET',
                            datatype: "json",
                            contentType: 'application/json; charset=utf-8',
                            async: false,
                            success: function (data) {
                                alert(data.results);
                            }
                        });

【讨论】:

  • 我想运行这个 ajax 调用 - 每当我的页面加载时......我该怎么做?
  • 假设你正在使用一个按钮来加载 html 页面,点击该按钮你将不得不调用这个 ajax 方法。
  • 在这个按钮上 $('#somepage').click(function () { //write ajax code here }) ;
  • 我无法使用按钮。
  • 无论您使用什么来访问该页面,都可以为此进行 ajax 调用。
猜你喜欢
  • 2020-10-01
  • 2023-03-21
  • 2019-07-01
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多