Mvc视图编写自定义辅助方法:
为了是Asp.net MVC变成经典的Asp页面,如果代码比较多,不仅仅是一个属性,包含一些操作是,就应该编写自己的辅助方法
示例:
View:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true"
CodeBehind="~/Views/CustemHlper/TestHelper.cs" Inherits="MvcTest.Views.CustemHlper.TestHelper" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
CustemHleper
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
CustemHleper</h2>
<table>
<%
int rowindex = 0;
foreach (var book in ViewData.Model)
{ %>
<%if (rowindex++ % 2 == 0)
{ %>
<tr style="background-color: Yellow">
<%}
else
{ %>
<tr>
<%} %>
<td>
<%= book.Book_no%>
</td>
<td>
<%= WriteDetailLink(book) %>
</td>
<td>
<%= book.Book_name%>
</td>
<td>
<%= book.Book_author%>
</td>
</tr>
<%} %>
</table>
</asp:Content>
Code_Cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcTest.Models;
using System.Web.Mvc.Html;
namespace MvcTest.Views.CustemHlper
{
public partial class TestHelper:ViewPage<IList<Books>>
{
protected string WriteDetailLink(Books book)
{
return Html.ActionLink("Detail", "Detail", new { id=book.Book_no}).ToString();
}
}
}
Controller:
public ActionResult TestHelper()
{
Books book = new Books { Book_no = "SZ1000090", Book_author = "lin.su", Book_name = "大话设计模式" };
IList<Books> list = new List<Books>();
list.Add(book);
ViewData.Model = list;
return View();
}
如果辅助方法是针对特定视图,这种方法很好,如果希望编写一个更大范围中使用的辅助方法,那就必须编写为核心Htm辅助方法的对象扩展方法,如编写一个table 的隔行换色:
示例:
要为每个Html创建一个扩展方法,需要使用下面的语法;
public static string AlternateRowColor(this System.Web.Mvc.HtmlHelper herlper, ....);
public static class TableHelper
{
public static string AlternateRowColor(this System.Web.Mvc.HtmlHelper herlper, int row, string color)
{
if (row % 2 == 0)
{
return "background-color:" + color;
}
else
{
return "";
}
}
}
在View页面这样就可以调用:
示例;
<tr style="<%=Htm.AlternateRowColor(rowindex ++,"Yellow")%>">