如何将此JavaScript代码链接到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 })
})
});
锚标签:
<a id="@c.Key" href ="???" onclick="???">@c.Key</a>
brandsOfACategory
操作方法:
[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
是:
@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>
答案 0 :(得分:1)
您可以这样编写锚标记-
<a id="@c.Key" href ="javascript:void(0);" onclick="postBrands(@c.Key)">@c.Key</a> //replace postBrands with desired function name
然后在javascript中定义将包含发布请求的函数-
function postBrands(key) {
$.ajax({
type: 'POST',
url: '@Url.Action("/brandsOfACategory")',
contentType: 'application/json; charset:utf-8',
data: JSON.stringify({ id: key })
})
}
答案 1 :(得分:0)
您可以放入href,然后在客户端点击代码中提取href
:
<a id="@c.Key" href ="@Url.Action("actionName","controllerName")">@c.Key</a>
,在click事件中,您可以编写以下内容:
$(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 })
})