随笔 - 14  文章 - 0 评论 - 124 阅读 - 22784
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

最近的项目是用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() %>

就先说这么多,有些已经记不太清了,错误的地方或说的不全面的地方,希望大家指正与补充。
posted on   Coolin  阅读(4020)  评论(37编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
点击右上角即可分享
微信分享提示