MVC 帮助类/公共方法

来源:互联网 发布:网络草花机 编辑:程序博客网 时间:2024/06/01 07:44

Html.DropDownList/Html.DropDownListFor

SelectList

ViewDate["GenreId"]new SelectList(集合,"显示的字段","值",默认选择) 用于 Html.DropDownList

一、非强类型:

Controller:
ViewData["AreId"] = from a in rp.GetArea()
                               select new SelectListItem { 
                               Text=a.AreaName,
                               Value=a.AreaId.ToString()
                               };
View:

@Html.DropDownList("AreId")

@Html.DropDownList("AreId",ViewBag.AreId as SelectList)

还可以给其加上一个默认选项:@Html.DropDownList("AreId", "请选择");

二、强类型:

DropDownListFor常用的是两个参数的重载,第一参数是生成的select的名称,第二个参数是数据,用于将绑定数据源至DropDownListFor
Modle:
   public class SettingsViewModel
   {
       Repository rp =new Repository();
       public string ListName { get; set; }  
       public  IEnumerable<SelectListItem> GetSelectList()
       {
               var selectList = rp.GetArea().Select(a => new SelectListItem { 
                               Text=a.AreaName,
                               Value=a.AreaId.ToString()
                               });
               return selectList;
           }
       } 
Controller:
       public ActionResult Index()
       {
           return View(new SettingsViewModel());
       }
View:
@model Mvc3Applicationtest2.Models.SettingsViewModel

@Html.DropDownListFor(m=>m.ListName,Model.GetSelectList(),"请选择")

UrlHelper辅助方法

Action

Content

RouteUrl

一、UrlHelper.Action

UrlHelper的Action方法 用于生成一个URL地址,它的使用方法为

当前Controller下Index这个Action <%=Url.Action(“Index”)%> index

当前Controller下Index这个Action <%=Url.Action(“Index”,new{id=1})%> index?id=1

EiceController下Index这个Action <%=Url.Action(“Index”,"Eice")%> /eice/index

EiceController下Index这个Action <%=Url.Action(“Index”,"Eice",new{id=1})%> /eice/index?id=1

例如我在View中写Url.Action("Index","Home"),运行后则会生成/Home/Index这个地址,如果你的系统中的URL Routing规则总是变化的话这个Helper则是你必备之选.

二、UrlHelper.Encode

这也是UrlHelper的一个方法 使用方法 如<%=Url.Encode("中文")%>功能与Server.UrlEncode相同,这里不多说了

三、UrlHelper.Content

用于服务器路径转换为绝对路径。

<%=Url.Content("~/content/site.css") %>

最后的结果为

/content/site.css 
public virtual string RouteUrl(string routeName,Object routeValues,string protocol)

参数

routeName
类型:System.String
用于生成 URL 的路由的名称。
routeValues
类型:System.Object
一个包含路由参数的对象。 通过检查对象的属性,利用反射检索参数。 该对象通常是使用对象初始值设定项语法创建的。
protocol
类型:System.String
URL 协议,如“http”或“https”。

返回值

类型:System.String
完全限定 URL。

Html.Partial/RenderPartial //渲染部分视图

Html.Action/RenderAction//渲染执行控制器并显示结果

对于简单的没有任何逻辑的用户控件,推荐使用Html.Partial;对于需要设置一些Model的用户控件,推荐使用Html.Action。


许多时候我们会遇到如下场景在写一个编辑数据的页面时,我们通常会写如下代码1:<inputtype="text"value='<%=ViewData["title"] %>'name="title"/>由前篇我们所讲的Helper演化,我们思考,对于这种代码我们是不是也可以用一个Helper来自动绑定数据呢这当然是可以的,ASP.NET MVC提供了一个HtmlHelper用于生成有数据绑定的Html标签。1.ActionLink 其中最常用的就是Html.ActionLink1.1基本的使用方式 1: <%=Html.ActionLink("页面显示的文字", "Index", "Home")%>在UrlRouting规则为默认规则的情况下,它生成的HTML代码为1:<a href="/">页面显示的文字</a> ActionLink中的三个参数分别为 (显示的文字 Action Controller) 其中Controller可以省略,省略时指向同一Controller下的Action。1.2ActionLink中QueryString与Html属性设置1: 带有QueryString的写法 2: <%=Html.ActionLink("页面显示的文字", "Index", "Home", new { page=1 },null)%> 3:<%=Html.ActionLink("页面显示的文字", "Index", new { page=1 })%> 4: 有其它Html属性的写法 5: <%=Html.ActionLink("页面显示的文字", "Index", "Home", new { id="link1" })%>6: <%=Html.ActionLink("页面显示的文字", "Index",null, new { id="link1" })%> 7: QueryString与Html属性同时存在 8: <%=Html.ActionLink("页面显示的文字", "Index", "Home", new { page = 1 }, new { id = "link1" })%> 9: <%=Html.ActionLink("页面显示的文字","Index" , new { page = 1 }, new { id = "link1" })%> 其生成结果为:1: 带有QueryString的写法 2:<a href="/?page=1">页面显示的文字</a> 3:<a href="/?page=1">页面显示的文字</a> 4: 有其它Html属性的写法 5:<ahref="/?Length=4"id="link1">页面显示的文字</a> 6:<ahref="/"id="link1">页面显示的文字</a> 7: QueryString与Html属性同时存在 8:<ahref="/?page=1"id="link1">页面显示的文字</a> 9:<ahref="/?page=1"id="link1">页面显示的文字</a>这样就可以使用ActionLink生成近乎所有的地址连接了。注意,如果连接中不涉及到action及controller就没有必要使用ActionLink,而是直接写HTML代码就可以了,例如1:<ahref="#1">一章</a> 2:<ahref="javascript:void(0)"onclick="delete();">删除</a>
2.RouteLink2.1与ActionLink RouteLink与ActionLink相差无几,只是它的地址是由Route生成拿上面的例子1: <%=Html.ActionLink("页面显示的文字", "Index", "Home")%> 来说,如果用RouteLink来写就是1: <%=Html.RouteLink("页面显示的文字", new { controller="Home",action="Index"})%>而带上QueryString以及Html属性的ActionLink1: <%=Html.ActionLink("页面显示的文字", "Index" , new { page = 1 }, new { id ="link1" })%>就可以这样来写1: <%=Html.RouteLink("页面显示的文字", new { action = "index", page = 1 }, new { id="link1"})%>其实就是用一个新建立的RouteValueDictionary的对象(new{}所实例化的对象将会等价转换为RouteValueDictionary)来替原来的Action,Controller字符串的单独指定。2.2RouteLink使用Route规则 除了这些协同的用法,RouteLink还支持使用Route规则名来创建连接例如我们在Global.asax文件中添加一个Route规则1: routes.MapRoute( 2:"about",//这是规则名 3:"about",//url 4:new {controller = "Home", action = "about"} 5: ); 那么我们就可以使用这个Route规则1: <%=Html.RouteLink("关于", "about", new { })%> 2: <%=Html.RouteLink("关于", "about", new { page = 1 })%> 3: <%=Html.RouteLink("关于", "about", new { page = 1 }, new { id = "link1" })%>来生成如下的HTML:1:<ahref="/about">关于</a> 2:<ahref="/about?page=1">关于</a> 3:<ahref="/about?page=1"id="link1">关于</a>3.表单 很多情况下是要生成表单元素的,正如文章开始所述,修改一个内容的情况下,我们可能要将数据与表单绑定。3.1生成Form 我们当然可以使用纯的Html代码或UrlHelper来生成一个Form。如1:<formaction="/home/index"method="post"> 2:</form>1:<formaction="<%=Url.Action("Index","Home")%>"method="post"> 2:</form>但是因为是在HTML的属性中,所以还是难以维护,幸好ASP.NET MVC为我们提供了一个Helper,我们可以通过以下两种方式生成一个Form:1: <%using(Html.BeginForm("index","home",FormMethod.Post)){%> 2: 表单内容 3: <%} %> 4: <%Html.BeginForm("index", "home", FormMethod.Post);//注意这里没有=输出%> 5: 表单内容 6: <%Html.EndForm(); %>BeginForm方法类似于ActionLink的调用方式,所以ASP.NET MVC还提供了BeginRouteForm这种方法。当然这里我们也可以使用new{}来为form的action增加querystring或HTML属性,方法与前面介绍的大同小异,参见方法列表即可。3.2表单元素 ASP.NET MVC提供了多种表单元素的Helper。其中包括:TextBox(类似input type=text,下面类似)、TextArea、DropDownList(select)、CheckBoxHidden、ListBox、Password、RadionButton。注意:因为<input type=”submit” />一般情况下是不会绑定数据的所以ASP.NET MVC并未提供此Helper(曾经提供过在preview2之前)。如果我们想提供一个input type=text 它的name为t1则以下代码:1: <%=Html.TextBox("t1") %>3.3表单元素绑定 如果我们想要让上文中的t1初始时就有一个值,比如 “重典”那么我们可以按以下方式1: <%=Html.TextBox("t1","重典") %>如果数据是从数据库中读取,即得到数据是从Action中获取的,那么我们可以在Action中使用ViewData传递Action:1: ViewData["name"]="重典";View:1: <%=Html.TextBox("t1",ViewData["name"]) %>以上方法看似简单,其实ASP.NET MVC为我们提供了更为简便的绑定方式---只要保证ViewData的Key与Helper所生成元素的name保持一致就可以自动绑定:Action:1: ViewData["t1"]="重典";View:1: <%=Html.TextBox("t1") %>这样就可以自动绑定了3.4列表数据显示与绑定 像TextBox这种值单一的数据比较容易,但是存在的数据比较多的DropDownList或ListBox应该怎么绑定数据及初始化值呢,我们来看看下面的例子:Action:1: ViewData["sel1"] = new SelectList( 2:new[] {1, 2, 3} /*列表内容可以是数组*/ 3: , 3 /*默认值,可以是从数据库读出的*/ 4: );View:1: <%=Html.DropDownList("sel1")%>这样就可以将列表内容、默认值、以及表单元素三者绑定在一起了。而我们的列表内容并不是任何情况下都是数组的,大多情况下还是Key-Value对居多。我们可以使用以下方式:1: List<SelectListItem> list = new List<SelectListItem> 2: { 3:new SelectListItem {Text = "重典", Value = "1"}, 4:new SelectListItem {Text = "邹健", Value = "2"}, 5: }; 6: ViewData["sel1"] = new SelectList( 7: list /*列表内容可以是数组*/ 8: , "2"/*默认值,可以是从数据库读出的*/ 9:  );10.TextBox , Hidden <%=Html.TextBox("input1") %> <%=Html.TextBox("input2",Model.CategoryName,new{ @style = "width:300px;" }) %> <%=Html.TextBox("input3", ViewData["Name"],new{ @style = "width:300px;" }) %> <%=Html.TextBoxFor(a => a.CategoryName, new { @style = "width:300px;" })%>   生成结果:   <input id="input1" name="input1" type="text"value="" /> <input id="input2" name="input2" style="width:300px;" type="text"value="Beverages" /> <input id="input3" name="input3" style="width:300px;" type="text"value="" /> <input id="CategoryName" name="CategoryName" style="width:300px;" type="text"value="Beverages" />
@Html.Hidden("wizardStep",1)
<input id="wizardStep" type="hidden" value="1"/>
@Html.HiddenFor(m=>m.WizardStep)‍‍‍‍‍11.TextArea‍‍<%=Html.TextArea("input5", Model.CategoryName, 3, 9,null)%> <%=Html.TextAreaFor(a => a.CategoryName, 3, 3, null)%> 生成结果: <textarea cols="9" id="input5" name="input5" rows="3">Beverages</textarea>‍ <textarea cols="3" id="CategoryName" name="CategoryName" rows="3">Beverages</textarea>‍12.CheckBox<%=Html.CheckBox("chk1",true) %><%=Html.CheckBox("chk1", new { @class="checkBox"}) %><%=Html.CheckBoxFor(a =>a.IsVaild, new { @class = "checkBox" })%>生成结果:   <input checked="checked" id="chk1" name="chk1" type="checkbox"value="true" /><input name="chk1" type="hidden"value="false" />‍<input class="checkBox" id="chk1" name="chk1" type="checkbox"value="true" /><input name="chk1" type="hidden"value="false" /><input checked="checked"class="checkBox" id="IsVaild" name="IsVaild" type="checkbox"value="true" /><input name="IsVaild" type="hidden"value="false" />‍13.‍ListBox<%=Html.ListBox("lstBox1",(SelectList)ViewData["Categories"])%>‍ <%=Html.ListBoxFor(a => a.CategoryName, (SelectList)ViewData["Categories"])%>‍   生成结果: <select id="lstBox1" multiple="multiple" name="lstBox1">‍ <option value="1">Beverages</option>‍ <option value="2">Condiments</option> <option selected="selected"value="3">Confections</option>‍ <option value="4">Dairy Products</option> <option value="5">Grains/Cereals</option>‍ <option value="6">Meat/Poultry</option> <option value="7">Produce</option>‍ <option value="8">Seafood</option>‍ </select> <select id="CategoryName" multiple="multiple" name="CategoryName">‍ <option value="1">Beverages</option> <option value="2">Condiments</option>‍ <option value="3">Confections</option> <option value="4">Dairy Products</option> <option value="5">Grains/Cereals</option>‍ <option value="6">Meat/Poultry</option> <option value="7">Produce</option>‍ <option value="8">Seafood</option> </select>14.DropDownList‍<%= Html.DropDownList("ddl1", (SelectList)ViewData["Categories"], "--Select One--")%>‍ <%=Html.DropDownListFor(a => a.CategoryName, (SelectList)ViewData["Categories"], "--Select One--", new { @class = "dropdownlist" })%>   生成结果: <select id="ddl1" name="ddl1">‍ <option value="">--Select One--</option>‍ <option value="1">Beverages</option>‍ <option value="2">Condiments</option> <option selected="selected"value="3">Confections</option> <option value="4">Dairy Products</option> <option value="5">Grains/Cereals</option>‍ <option value="6">Meat/Poultry</option> <option value="7">Produce</option>‍ <option value="8">Seafood</option>‍ </select> <select class="dropdownlist" id="CategoryName" name="CategoryName">‍<option value="">--Select One--</option> <option value="1">Beverages</option>‍<option value="2">Condiments</option> <option value="3">Confections</option>‍<option value="4">Dairy Products</option><option value="5">Grains/Cereals</option><option value="6">Meat/Poultry</option><option value="7">Produce</option>‍<option value="8">Seafood</option> </select>‍15.Partial 视图模板 webform里叫自定义控件。功能都是为了复用。但使用上自定义控件真的很难用好。<% Html.RenderPartial("DinnerForm"); %>  看清楚了没有等号的。


1、 @Html.Label()
返回一个 HTML label 元素和由指定表达式表示的属性的属性名称。
参数:string expression,string labelText
expression:一个表达式表示要显示的属性
labelText:显示文字
例: 

[html] view plaincopy
  1. @Html.Label("weight")       输出:<label for="weight">weight</label>  
  2. abel("name","姓名")  输出:<label for="name">姓名</label>  

2、 @Html.LabelFor()
和@Html.Label()类似,只是主要针对强类型
例:
[html] view plaincopy
  1.        @Html.LabelFor(model=>mode.Name) 输出:  <label for="Name">Name</label>  
  2. @Html.LabelFor(model=>mode.Name,"姓名") 输出:<label for="name">姓名</label>  
  3. 如果在上面实体添加[DisplayName("姓名")]特性(引用System.ComponentModel;)则会显示:  
  4. <label for="Name">姓名</label>用于显示汉字很方便  

3、 @Html.LabelForModel()
例:@Html.LabelForModel("name") 输出: <label for="">name</label>

Editor标签,表示应用程序中的Input表单控件,在EditorExtensions实现
1、 @Html.Editor() 
返回一个由表达式表示的对象中的每个属性所对应的input元素
例:
[html] view plaincopy
  1. a、@Html.Editor("name") 输出;<input class="text-box single-line" id="name" name="name" type="text" value="" />  

b、在加载的时候为input初始化值,这里用asp.net MVC新增的ViewBag属性;
[html] view plaincopy
  1.      @{  
  2.     ViewBag.NameValue="张三"; // NameValue为动态类型  
  3.     或者  
  4.     ViewData["NameValue"]="张三";  
  5. }  
  6. @Html.Editor("NameValue") 输出<input class="text-box single-line" id="NameValue" name="NameValue" type="text" value="张三" />  

c、@Html.Editor("name",Model.Name)
  第二个参数为object additionalViewData 参数 主要为视图模型的数据 (Model为System.Web.Mvc.Model对象,在加载页面引用@model Student 对象),
  但不知道这样Input为什么没显示默认值。不知道不是不asp.net mvc3中不支持了,希望知道的给予说明下。
2、 @Html.EditorFor()
返回一个由表达式表示的对象中的每个属性所对应的input元素,主要是针对强类型,一般这种方式用得多些
a、@Html.EditorFor(mode=>mode.Name)
如果返回的View给Student实体赋予值,则输出输出<input class="text-box single-line" id="Name" name="Name" type="text" value="默认值" />否则Value为"";
b、@Html.EditorFor(mode=>mode.Name,"templateName")
第二个参数为模版名称,模版的定义:
首先在目录View/Shared/建立文件夹EditorTemplates/templateName.cshtml 即:View/Shared/EditorTemplates/templateName.cshtml
注:这务必用EditorTemplates作为文件夹
templateName.cshtml代码为: @Html.DropDownList("",new SelectList(new []{"1","2","3"}))表示一个值为1,2,3的下拉列表
这时就可以调用@Html.EditorFor(mode=>mode.Name,"templateName"),则显示成一个下拉列表,如果模版中设置的一个文本框则显示成文本框。
同时,也可以在实体Student中的Name属性加上[UIHint("templateName")]特性 如果加上这个则可在调用的时候不用显示指定模版名称
用@Html.EditorFor(mode=>mode.Name)即可显示成下拉框,同时所有用这个字段的都将变成下拉列表
相当与Html中的Input控件
@Html.EditorFor(model=>model.Age)

页面显示为:   <input id="Age" name="Age" type="text" value="" />

Html.ValidationSummary

Html.ValidationSummary(false)//不显示那些与模型属性相关的错误  

@Html.ValidationSummary(true) //只显示ModelState中的模型本身错误

@Html.ValidationSummary(true,"")

3、 @Html.EditorForModel()

如果使用默认值,不带任何参数,则循环显示Model中所有的信息,不过需要放在循环中
如:<input class="text-box single-line" id="Name" name="Name" type="text" value="" />
   <input class="text-box single-line" id="Age" name="Age" type="text" value="" />

1.Html.BeginForm()

      该方法用于构建一个From表单的开始,他的构造方法为:

      Html.BeginForm("ActionName","ControllerName",FormMethod.method)

      一般构建一个表单结构如下

     <% using(Html.BeginForm ("index","home",FormMethod.Post)){ %> 

      。。。。。。

     <%} %>

      他将在客户端产生一个类似<form action="/account/login" method="post"></form>标签

   

    2.现在开始创建一个表单实例,首先在Index.aspx中构建一个表单

  <% using(Html.BeginForm ("index","home",FormMethod.Post)){ %>  
 帐号:<%=Html .TextBox ("username") %>
 <br/>
 密码:<%=Html .Password ("password") %>
 <br />
 <input type="submit" value="登录" />
 <%} %>

 

    3.在对应得控制器HomeController.cs中写入下面代码,传递出一个ViewData[]字典:

public ActionResult Index()
        {
            string struser = Request.Form["username"];
            string strpass = Request.Form["password"];
            ViewData["w"] = "你的账号是:" + struser + "你的密码是:" + strpass;
            return View();
        }

 

    4.在Index.aspx中写接受传值

    <%=ViewData ["w"] %>

添加属性和样式  

1.添加属性:@Html.Label("CnAddressmodify","", new { maxlength="90";target="_blank;Data_validatable=true" })

//Data-validatable=true

2.添加样式:@Html.TextBox("EnAddressmodify","",new {@class="EnAddressmodify",style="width:86px;"})

Html.TextArea("text","hello <br/> world")

0 0
原创粉丝点击