[代码]Asp.net MVC HtmlHelper类应用实例

尽管MVC framework已经出来几个月了,不过这方面的资料却很少,大部分都是抄来抄去,特别是更细节的对于MVC封装的HtmlHlper类的介绍更是少之又少,有也只是简单的例子,没有涉及到数据库层的实例,实际应用中往往数据都是从数据库中读取出来的,因此,没办法只能啃源码啦,不容易啊,下面是我应用过程中整理的组件绑定数据组件的代码,随着应用会陆续增加。
Html.Select 应用实例:
Conroller
[code]
namespace Tang.Controllers
{
public class ChannelController : Controller
{
public void Index()
{
RenderView("Index");
}
public void Manage()
{
RenderView("Index");
}
public void Update()
{
//RenderView();
}
public void New()
{
//读取数据库
SysConst sysConst = SysConst.Instance();
//返回数据集给页面
ViewData["ds"]=sysConst.ChannelSet;
RenderView("Create");
}
}
}
[/code]
页面:
[code]
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Admin.Master" AutoEventWireup="true" CodeBehind="Create.aspx.cs" Inherits="Tang.Views.Channel.Create" %>
<%@ Import Namespace="Tang.Models.Communion" %>
<%@ Import Namespace="Tang.Controllers" %>



<% string [] states =new string[]{"开放", "关闭","删除"}; //读取数据集,给select组件赋初值 System.Data.DataSet ds = (System.Data.DataSet)ViewData["ds"]; //设置默认选择值 ArrayList selectvalues = new ArrayList(); selectvalues.Add(1); %>

<%=Html.Select("parentChannelId", ds, "ChannelName", "Identifier",selectvalues)%>
<%=Html.TextBox("Channel.ChannelName") %>
<%=Html.Select("state", states)%>
描述:
<%=Html.TextArea("Channel.Description",null) %>

<%=Html.SubmitButton("保存") %>


[/code]
转载老外的例子:
[code]
<% //Sample Data string [] songs=new string[]{"Robot Rock (Daft Punk)","Stairway to Heaven (Zeppeling)", "New Slang (Shins)"}; string [] movies=new string[]{"Tron","Big Trouble In Little China", "Say Anything"}; string [] zodiac =new string[]{"Aries", "Taurus","Gemini","Cancer","Leo", "Virgo","Libra","Scorpio","Sag","Capricorn","Aquarius","Haack"}; %>
Sign:
<%=Html.Select("myZodiac",zodiac) %>
Sign (select Haacked):
<%=Html.Select("myZodiac",zodiac,"Haacked") %>
Favorite Movie:
<%=Html.CheckBoxList("favMovie",movies).ToFormattedList("

  • {0}
  • ") %>
    Favorite Movie, List :
    <%=Html.ListBox("favMovie",movies,new string[]{"Say Anything"}) %>
    Favorite Movie, List, Long, Mult (select "Say Anything" and "Tron")i:
    <%=Html.ListBox("favMovie",movies,20,true,new string[]{"Say Anything", "Tron"}) %>
    Favorite Songs (Select Shins):
    <%=Html.CheckBoxList("favSongs",songs,new string[]{"New Slang (Shins)"}) .ToFormattedList("

  • {0}
  • ") %>
    Favorite Songs:
    <%=Html.CheckBoxList("favSongs", songs).ToFormattedList("

  • {0}
  • ")%>
    Favorite Songs, Radio:
    <%=Html.RadioButtonList("favSongs", songs,"Robot Rock (Daft Punk)") .ToFormattedList("

  • {0}
  • ")%>
    [/code]