zoukankan      html  css  js  c++  java
  • MVC3学习 六 HtmlHelper的使用与扩展

    使用链接时,如果传统的跳转方式如:

    <a href="Home/Index>返回</a>
    

     如果将路由的默认配置

       routes.MapRoute(
                    "Default", // Route name
                    "{controller}/{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                );

    修改为:

       routes.MapRoute(
                    "Default", // Route name
                    "{controller}-{action}/{id}", // URL with parameters
                    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                );

    则原始的跳转就会失效。所以在跳转时,要使用

    @Html.ActionLink("返回","Index","Home")

    这样,不管以后的路由规则如何变化,链接照样还可以使用。

    显示数据的细节:

    MVC中,控件的数据绑定都是先根据name到viewdata中去寻找key值,如果存在,则绑定数据,所以在controller中,直接将数据绑定到viewdata中,key设置为控件的name名,就可以直接显示了,如:

    controller中:ViewData["id"]="1";

    view中:@Html.TextBox("id"),这样,在页面加载时,会直接将这个“1”绑定到TextBox中,同样绑定Dropdownlist时,也可以同样用这种方式。

    <% : %>与<% = %>的区别

    <% : %>会将代码以安全的方式显示在view中,比如在controller中,Viewdata["message"]="<script>alert("您好")</script>",

    <% : Viewdata["message"]%>显示时,会将"<"自动转码为html的格式,也就是说不会弹出提示。

    <%=Viewdata["message"]%>显示时,并不会转换,而是直接在页面弹出对话框。

    扩展Htmlhelper

    扩展时需要注意三个要素,即:静态类,静态方法,this关键字。

    在models中新建一个类,代码如下:

    namespace System.Web.Mvc
    {
        //扩展HtmlHelper方法
        public static class MyHtmlHelperExt
        {
         //扩展HtmlHelper方法
    public static string Mylable(this HtmlHelper helper, string txt) { return string.Format("<p>您好,{0}</p>", txt); } public static HtmlString MyHtmlStringLable(this HtmlHelper helper, string txt) { return new HtmlString(string.Format("<p>您好,{0}</p>", txt)); } } }

    这里首先需要注意,namespace System.Web.Mvc,如果不将默认的命名空间变成和HtmlHelper一致的话,在页面中不导入models的命名空间会无法使用,所以若想在其他页面中直接使用,就需要将命名

    空间和HtmlHelper一致,这样能使用HtmlHelper的页面,也同样能够使用扩展的方法。

    然后需要注意的是第一个扩展的方法,如果直接返回string类型,而不返回HtmlString类型时,那么返回的字符串会被自动转换成html格式,也就是说p标签无效,而微软做的直接就可以返回标签,是因为返回

    的是HtmlString类型,所以需要将返回类型设置为HtmlString。

  • 相关阅读:
    机器学习实战
    python中的上下文管理器
    python中的参数传递
    SecureCRT在mac下无法输入中断命令
    Vim练级攻略(转)
    09_MySQL DQL_SQL99标准中的多表查询(外连接)
    08_MySQL DQL_SQL99标准中的多表查询(内连接)
    07_MySQL DQL_多表查询_等值内连接
    06_MySQL DQL_分组查询
    05_MySQL常见函数_分组函数
  • 原文地址:https://www.cnblogs.com/y8932809/p/4387070.html
Copyright © 2011-2022 走看看