我试图在asp.net环境中通过jquery运行javascript函数。但是无论我尝试什么,单击按钮时该功能都不会运行。我试过不使用jquery,并使html输入控制器id非动态。然而似乎没有任何作用。非常感谢任何帮助,这是代码。
@model IEnumerable<NotesWebApp.Models.Product>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<div style="height:400px; overflow-y: scroll">
@foreach (var item in Model)
{
<div>
<p>@item.Name</p>
<p align="center">
@*
@Html.ActionLink("Add Note", "AddNote", new { id = item.ID }) |
@Html.ActionLink("Show Notes", "ViewNotes", new { id = item.ID })
*@
<input id="@item.ID"type="submit" value="View Notes" class="btn btn-default"/>
<script src="https://code.jquery.com/jquery-1.10.2.js">
$("#@item.ID").click(function () {
window.alert("Works");
});
</script>
</p>
</div>
<div id="bob" style="display:none">
<table style="align-items:center" class="table">
<tr>
<th>
Note Text
</th>
<th>
Create Date
</th>
<th>
Name
</th>
<th></th>
</tr>
@foreach (var note in item.ProductNotes)
{
<tr>
<td>
@Html.DisplayFor(modelItem => note.NoteText)
</td>
<td>
@Html.DisplayFor(modelItem => note.CreateDate)
</td>
<td>
@Html.DisplayFor(modelItem => note.Archived)
</td>
<td>
@Html.DisplayFor(modelItem => note.Product.Name)
</td>
@*
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>*@
</tr>
}
</table>
</div>
}
</div>
答案 0 :(得分:0)
对于页面启动代码,JQuery调用需要位于$( document ).ready(function() {...}
块内才能工作。此外,<script>...</script>
标记可以包含src属性或实际代码,不能同时包含。试试这个:
<script src="https://code.jquery.com/jquery-1.10.2.js"/>
<script>
$( document ).ready(function() {
$("#@item.ID").click(function () {
window.alert("Works");
})
});
</script>
答案 1 :(得分:0)
理想情况下,您希望为每个产品项使用部分视图,以便代码更清晰,更易于处理。
查看Chapter 8 Sample Code of Pro ASP.NET MVC 5 by Adam Freeman.
例如,
@model SportsStore.WebUI.Models.ProductsListViewModel
@foreach (var p in Model.Products) {
@Html.Partial("ProductSummary", p)
}
@model SportsStore.Domain.Entities.Product
<div class="well">
<h3>
<strong>@Model.Name</strong>
<span class="pull-right label label-primary">@Model.Price.ToString("c")</span>
</h3>
@using (Html.BeginForm("AddToCart", "Cart")) {
<div class="pull-right">
@Html.HiddenFor(x => x.ProductID)
@Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" class="btn btn-success" value="Add to cart" />
</div>
}
<span class="lead"> @Model.Description</span>
</div>
public RedirectToRouteResult AddToCart(int productId, string returnUrl) {
Product product = repository.Products
.FirstOrDefault(p => p.ProductID == productId);
if (product != null) {
GetCart().AddItem(product, 1);
}
return RedirectToAction("Index", new { returnUrl });
}