Strongly typed page references in ASP.NET

题目来自与 CodeProject上的一篇文章。

在asp.net的程序中,页面跳转的处理是很平常事情,通常的做法是定义一个url,然后执行跳转:

string  url  =   " ~/Print/Printitem.aspx?id= "   +  item.Id  +   " &format= "   +  itemFormat;
Response.Redirect(url);

文章的作者对这中做法提出了异议,他认为这样的页面引用不是“强类型”的。那么什么样的页面引用是强类型的呢,作者给出了一个例子:在页面(Page)的内部定义页面自己的url,同时定义个获得该url的静态方法(必须是静态的,否则从页面的外部无法访问了,因为没有page的实例),当我们需要做跳转处理时就调用该静态方法得到url,当然也包括需要传递给QueryString的参数。

         /// <summary>
        
/// Construct a URL to self with an Item and an ItemFormat
        
/// </summary>

         public   static   string  UrlToSelf(Item item, Itemformat itemFormat)
        
{
            
return string.Format("~/print/printitem.aspx?id={0}&format={1}", item.id, itemFormat.ToString());
        }

        
        
/// <summary>
        
/// Construct a URL to self with just an Item (will use the default ItemFormat)
        
/// </summary>

         public   static   string  UrlToSelf(Item item)
        
{
            
return UrlToSelf(item, ItemFormat.Default);
        }

         

页面跳转就变成了这样:

string  url = SomePage.UrlToSelf;
Response.Redirect(url);

这样做的好处是当我们要移动页面时不需要满世界地查找该页面的引用(页面的地址)然后将它们修正,相反我们只需要修改该页面内部定义的url即可。

这是一个不错的处理方式,事实上以强类型方式处理页面的引用已经有人做了大量的工作,比如 PageMethods就是一个这样的工具:

PageMethods allows us to enforce strong typing when calling a new web page, and provides an intuitive navigation model when coding our application.

关于PageMethods的具体信息可以参看它的 官方网站

PageMethods是一个自动生成页面引用的工具,我并没有用它来处理页面的跳转,而是采用了一种替代的方式:定义个专门处理页面跳转的类,它只包含静态的方法。

下面是一段例子:
/// <summary>
/// Summary description for PageMethods
/// </summary>

public   class  PageMethods
{
    
Asset

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值