设计ASP.NET应用程序的七大绝招
随着微软.net的流行,asp.net越来越为广大开发人员所接受。作为asp.net的开发人员,我们不仅需要掌握其基本的原理,更要多多实践,从实践中获取真正的开发本领。在我们的实际开发中,往往基本的原理满足不了开发需求,我们更多的要积累一些开发技巧,本文就向大家介绍一些实用技巧,希望对大家的开发有所裨益。
1. ~ 的用法一般的情况下,我们是使用./../ 这样的相对路径来确定和规划我们的资源(比如图片、资源文件),但这种方式下在我们部署应用的时候,可能会出错,另外对于.ascx的控件中如果包含了一个图片,而这个控件被我们在不同层次的两个的aspx文件分别引用时,问题就会出现了。 ~/image/about.bmp 是一种非常好的方法,它以web应用程序的根为起始点,这样使得比你使用./image/about.bmp这样的方式要更加灵活和方便。有一点不好,是这种方式是在asp.net运行时动态解析的,所以在ide设计模式中,你可能不能预览它。
2. 在刷新和提交页面后,保存你的页面滚动条的位置经常有这样的情况,我们需要用户提交一个表单,但是表单中有超过500+个?控件或文本框要填写,也就是说用户需要拉动ie的滚动条才能够填得完,那么假如用户正在可见ie范围的2/3处,选择了一个组合框的值,很不幸组合框是服务器端的,那么也就意味着页面会提交一次,而当用户再看见刷新过的页面时,页面确定在3/1的地方也就是显示在页面最开始的地方,用户只有拖动鼠标,然后接着刚刚的地方再填写剩下的250个控件,很不幸,370个控件又需要他选择一下? 用下面的方法可以很快地确定和记住你提交前的位置。
网上的old dog learns new tricks也有一个类似的例子maintain scroll position in any page element,不过他使用了web behavior这意味着你需要使用一个.htc文件
private sub retainscrollposition() dim savescrollposition as new stringbuilder
dim setscrollposition as new stringbuilder registerhiddenfield("__scrollpos", "0")
savescrollposition.append("<script language='javascript'>")
savescrollposition.append("function savescrollposition() {")
savescrollposition.append(" document.forms[0].__scrollpos.value = thebody.scrolltop;")
savescrollposition.append("}")
savescrollposition.append("thebody.onscroll=savescrollposition;")
savescrollposition.append("</script>") registerstartupscript("savescroll", savescrollposition.tostring()) if (page.ispostback = true) then setscrollposition.append("<script language='javascript'>")
setscrollposition.append("function setscrollposition() {")
setscrollposition.append(" thebody.scrolltop = " & request("__scrollpos") & ";")
setscrollposition.append("}")
setscrollposition.append("thebody.onload=setscrollposition;")
setscrollposition.append("</script>")
registerstartupscript("setscroll", setscrollposition.tostring()) end if end sub private sub page_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load
retainscrollposition()
end sub
3. datalist使用不同风格的模板这招也非常实用,你可以制作两个不同的模板或表现形式,分别以.ascx控件的形式保存,运行时根据某个条件动态的选择使用其中的一个模板,另外scottgu认为itemdatabound方法也可以定制你显示的表现,比如加亮某个元素或是加一个促销广告图等等。
dim theme as string
theme = dropdownlist1.selectedvalue datalist1.itemtemplate = page.loadtemplate(theme & ".ascx") ---cool
datalist1.datasource = ds
datalist1.databind()
4. 设置服务器端控件的焦点
private sub setfocus(byval controltofocus as control)
dim scriptfunction as new stringbuilder
dim scriptclientid as string scriptclientid = controltofocus.clientid
scriptfunction.append("<script language='javascript'>")
scriptfunction.append("document.getelementbyid('" & scriptclientid & "').focus();")
scriptfunction.append("</script>")
registerstartupscript("focus", scriptfunction.tostring())
end sub private sub page_load(byval sender as system.object, byval e as system.eventargs) handles mybase.load
if (page.ispostback = false) then
setfocus(textbox1)
end if
end sub
Tag: 绝招