loop
loop

Reputation: 9242

Invoking Controller method from Html page

I have created a Html page say SomePage.Html and I want that Whenever I visit this page a method should be called.

Suppose I created a Controller DefautController and It has method named - Get() then whenever I visited the "../SomePage.Html" then this "Get()" should be raised.

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>

DefaultController :-

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


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

How can I do that. I am very naive to this - WebApi/Asp.net thing. thanks :)

Upvotes: 0

Views: 1685

Answers (2)

V2Solutions - MS Team
V2Solutions - MS Team

Reputation: 1127

You have to give method name Get instead of index method in URL

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

Upvotes: 0

codebased
codebased

Reputation: 7073

You could use 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>

Upvotes: 1

Related Questions