MVC实用集锦(1)

最近的项目是用asp.net MVC开发的,所以希望从实际开发的角度,通过一些实例,帮助大家快速的开发asp.net MVC程序。
 1.创建控件,MVC中通过htmlHelper生成HTML标签。

1  <%=  Html.TextBox( " UserName " ) %>
2  <%=  Html.TextBox( " UserName " , " Coolin " ) %>
3  <%=  Html.TextBox( " UserName " , " Coolin " ,
            new  { @class  =   " className " ,disabled  =   true  }) %>

最后一项htmlAttributes,可以设置样式等属性。

2.RegisterRoutes带来了什么变化。通过VS创建一个MVC应用程序,会在Global.asax中看到下面的代码(我添加了第一条)
 
 1  routes.MapRoute(
 2           " Account " ,   
 3           " Account/List/{type} " ,                                 
 4           new  { controller  =   " Account " , action  =   "List "  }  
 5    );
 6 
 7  routes.MapRoute(
 8           " Default " ,                                                           
 9           " {controller}/{action}/{id} " ,                                 
10           new  { controller  =   " Home " , action  =   " Index " , id  =   ""  }  
11    );
      
现在看一下它带来的变化,假设view有如下代码

1  <%=  Html.ActionLink( " 男性 " " List " new  { type  =   " Man "  })  %>
2  <%=  Html.ActionLink( " 女性 " " List " new  { type  =   " Woman "  })  %>



1  <%=  Url.RouteUrl( " Account " new  { controller  =   " Account " , action  =   " List " , type =   " Man "  })  %>
2  <%=  Url.RouteUrl( " Account " new  { controller  =   " Account " , action  =   " List " , type =   " Woman "  })  %>

对应的Url应该是  localhost:XXXX/Account/List/Man 和 localhost:XXXX/Account/List/Woman
当然也可以不在Global.asax中注册那条规则,对应的Url就会变成大家熟悉的 localhost:XXXX/Account/List?type=Man。
顺便提一下我在开发中遇到过的一个问题,还以上面的例子为例,在程序的开发阶段,没有加入刚才那条规则,当我们在程序中加入了 sitemap(mvcsitemap),结果却是sitemap的路径永远不能指向Woman的路径,可能是sitemap不能通过 ?后面参数区分路径,后来加入了这条规则,url中去掉参数,问题解决了。

3.ajax异步请求controller
controller中有如下代码

1  public  ActionResult Delete(Guid id)
2  {
3      Delete(id);
4      return Json(new { success = true });
5  }

 view中代码如下

1  $.getJSON( <%=  Url.Action( " Delete " " Account " , new  { id = " xx-xx-xxx "  })  %>
2      function(result) {
3           if  (result.success) {
4               // 通过脚本移除此行
5              alert( " 删除成功! " )    
6          } 
7      });

4.扩展htmlHelper,方便在view中调用后台代码。
步骤 1)创建静态类 HtmlHelperExtension。
       2)引入 System.Web.Mvc 。
       3)创建需要的方法,例如:

1  public   static   string  FirstExtension( this  HtmlHelper htmlHelper)
2  {
3       return   " FirstExtension " ;
4  }

      4)在view中引入HtmlHelperExtension所在的命名空间(一定不要忘,我忘了很多次)
      5)在view中使用,例如 <%= Html.FirstExtension() %>

就先说这么多,有些已经记不太清了,错误的地方或说的不全面的地方,希望大家指正与补充。

你可能感兴趣的:(mvc)