R K
R K

Reputation: 133

How to link a JavaScript function to HTML anchor tag

How to link this JavaScript code to an anchor tag of HTML:

<script type="text/javascript">
    $(document).on('click', 'a', function () {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("/brandsOfACategory")',
            contentType: 'application/json; charset:utf-8',
            data: JSON.stringify({ id: this.id })
        })
    });

anchor tag:

<a id="@c.Key" href ="???" onclick="???">@c.Key</a>

brandsOfACategory action method:

[HttpPost]
    public ActionResult brandsOfACategory(string id)
    {
        var result = db.Items.Where(x => x.Category.Name.Equals(id)).Select(x => x.BrandID).ToList();
        var ListOfBrands = db.Brands.Where(t => result.Contains(t.BrandID)).ToList();
        return View(ListOfBrands);
    }

brandsOfACategory.cshtml is:

@model IEnumerable<OnlineStore.Models.Brand>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Brands in a Category</title>
</head>
<body>
    @foreach (var i in Model)
    {

        @i.Name.ToString();
    }
</body>
</html>

Upvotes: 1

Views: 1892

Answers (2)

Ashique
Ashique

Reputation: 355

You can write the anchor tag like this-

<a id="@c.Key" href ="javascript:void(0);" onclick="postBrands(@c.Key)">@c.Key</a> //replace postBrands with desired function name

Then define the function in the javascript which will contain the post request-

function postBrands(key) {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("/brandsOfACategory")',
            contentType: 'application/json; charset:utf-8',
            data: JSON.stringify({ id: key })
        })
}

Upvotes: 1

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You can put in href and then fetch the href in the client side click code:

<a id="@c.Key" href ="@Url.Action("actionName","controllerName")">@c.Key</a>

and in the click event you can write following:

$(document).on('click', 'a', function () {
    var Url = $(this).attr("href"); // get href value
    $.ajax({
        type: 'POST',
        url: Url, // use it here
        contentType: 'application/json; charset:utf-8',
        data: JSON.stringify({ id: this.id })
    })

Upvotes: 0

Related Questions