我之前問過這個問題(如何在asp.net mvc視圖中創建總計)。我認爲最簡單的方法是在模型中添加另一個項目,但我很好奇如何執行另一個使用Jquery的答案。在asp.net中使用jquery迭代表mvc
Showing totals in an asp.net MVC list view?
而且答案之一是迭代與jQuery表,並創建一個新的「總計」行。 我的jQuery技能是不存在的(我可以在我的視圖中創建一個hello world)。任何建議都會很棒。也許有一個我應該看的有用的jQuery庫。如果我也可以在這裏添加一個排序會很好。
有人可以給我一個例子,說明這可能如何工作。
下面是一些示例asp.net MVC 2的代碼,我想嘗試的工作,這爲
模型
namespace MvcScratch.Models
{
public class Thing
{
public string Name;
public int Value;
public Thing(string name, int value)
{
Name = name;
Value = value;
}
}
}
的控制器
public ActionResult Index()
{
List<Thing> myThings = new List<Thing>();
myThings.Add(new Thing("Thing 1",2));
myThings.Add(new Thing("Thing 2",3));
return View(myThings);
}
和視圖(用jQuery hello world)。
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcScratch.Models.Thing>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<h2>Index</h2>
<table>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<%-- <td>
<%: Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) %> |
<%: Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ })%> |
<%: Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })%>
</td>--%>
<td>
<%: item.Name %>
</td>
<td>
<%: item.Value %>
</td>
</tr>
<% } %>
</table>
<p>
<%: Html.ActionLink("Create New", "Create") %>
</p>
<script type="text/javascript">
$(document).ready(function() {
$("h2").click(function() {
alert("Hello world!");
});
});
</script>
</asp:Content>
我個人的觀點是在客戶端(通過使用ajax調用獲取數據並使用jQuery生成表)或者在服務器端進行。當你試圖混合他們兩個事情真的變得複雜。 – Ankur
@Ankur - 聽起來不錯。我想在這裏學習一些東西。你使用http://www.datatables.net/創建你的表或其他東西嗎? – Maestro1024
jquery完全是關於dom操作的。因此,在JQuery中,使用table tr和td元素創建表格的UI表示。如果你使用普通的javascript完成了DOM編程,那麼Jquery會很容易學習 – Ankur