打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
[翻译]你或许还为听说过的一些ASP.NET 2.0要诀 - 从这里开始出发....——lxinxuan‘s Blog - 博客园
原文链接:http://weblogs.asp.net/dwahlin/archive/2007/04/17/simple-asp-net-2-0-tips-and-tricks-that-you-may-or-may-not-have-heard-about.aspx 翻译不当请指正~~毕竟我这方面的能力还是蛮欠缺的,呵呵~~

在开发Web应用程序方面,Asp.net是一个令人敬畏的框架。如果你使用过一段时间,那么这就不是什么秘密了。它提供了一些十分强大的新特征,而你只需要些少量的代码就能实现。我曾经列出一个清单,上面是一些你可以只用少量或不用任何c#/VB.net代码就能实现的非常简单(甚至很酷)的功能。如果你有其他建议,可以添加评论,如果你的建议是一件能够容易应用的任务,我将进一步更新我的清单。

1、当页面PostBacks的时候,保持滚动条的位置。
在ASP.NET1.1中,当进行postback操作的时候,如果想保持滚动条的位置,那真是一件痛苦的事情,特别是当页面上有一个grid(表格?)而你想编辑某一具体行的时候。页面将会重新加载,滚动条位于页面顶端,而不是你期望的位置,这样你就不得不下拉滚动条。在ASP.net2.0中,你可以简单地在Pagedirective这里加上MaintainScrollPostionOnPostBack 属性(来实现同样的功能)。
<%@ Page Language="C#" MaintainScrollPositionOnPostback="true" AutoEventWireup="true" CodeFile="
" Inherits="
" %> 

2、当页面加载的时候,控件获得默认焦点。
这是另一件很简单的事情,而不用通过写javascrip脚本。如果你的页面上只有一个(或者两个)文本输入框,用户为什么非要点击文本框之后才能开始输入呢?光标难道就不能自动位于文本框,用户可以马上输入?使用HtmlForm控件的DefaultFocus 属性,你就可以很容易地做到。
<form id="frm" DefaultFocus="txtUserName" runat="server">
  

</form> 
 
3、当用户按下Enter键的时候,设置默认触发按钮。
在ASP.NET1.1中,这又是一件十分痛苦的事情。当用户按下Enter键的时候,你需要写一些javascript代码,来保证页面上适当的按钮触发一个服务器端“Click”事件。幸运的是,每当用户按下Enter键的时候,你现在可以使用HtmlForm的DefaultButton属性来设置点击哪一个按钮。还有一种情况,每当user(指光标是否更合适?)进入页面上不同面板触发不同的按钮,(这个情况下),就可以设置Panel控件的DefaultButton 属性。
<form id="frm" DefaultButton="btnSubmit" runat="server">
  

</form> 

4、容易地定位nested controls(嵌套控件?排列整齐的控件?表达不出来...呵呵~)。
在一个页面的控件层次中查找某些控件,确实是一件很头痛的事。但是如果你知道控件是如何嵌套(nest)的,你可以使用不怎么常用的快捷方式"$"来查找控件,而不用写递归代码。Ifyou‘re looking for a great way to recursively find a control (in caseswhere you don‘t know the exact control nesting) check out my good buddyMichael Palermo‘s blog entry.(这一句是广告,不翻了~)。以下代码展示了如何使用DefaultFocus 属性来给嵌套在FormView控件里面的文本框设置焦点。注意,用“$”来划定嵌套方式(nesting):
<form id="form1" runat="server" DefaultFocus="formVw$txtName">
    
<div>
        
<asp:FormView ID="formVw" runat="server">
            
<ItemTemplate>
                Name
: 
                
<asp:TextBox ID="txtName" runat="server" 
                    Text
=<%# Eval("FirstName") + " " + Eval("LastName") %> />
            
</ItemTemplate>
        
</asp:FormView>
    
</div>
</form>
在服务器端代码中调用FindControl()方法,也有一点小技巧。想了解更多细节,稍后请访问 I blogged about this 。这里有一个例子:
TextBox tb = this.FindControl("form1$formVw$txtName") as TextBox;
if (tb != null)
{
    
//Access TextBox control


5、Strongly-typed access to cross-page postback controls。(使用强类型方式访问跨页面提交控件?)
这一条比其他任何一点都更加involved(包含?不像,应该是不常用的意思吧),但是十分有用。一个页面提交信息到另一个页面,在这里ASP.NET2.0介绍了跨页面提交的概念。按钮提交数据到一个页面,把按钮的PostBackUrl属性设置为目标页面的名字,就是通过这种方式(实现跨页面提交)。
(不好意思啊,英超比赛开始了,不得不停下来看球了,剩下的内容以原文贴出,明天再译吧~~)
Normally,the posted data can be accessed by doing something likePreviousPage.FindControl("ControlID").  However, this requires a castif you need to access properties of the target control in the previouspage (which you normally need to do).  If you add a public propertyinto the code-behind page that initiates the postback operation, youcan access the property in a strongly-typed manner by adding thePreviousPageType directive into the target page of the postback.  Thatmay sound a little confusing if you haven‘t done it so let me explain alittle more.

If you have a page called Default.aspx that exposes a publicproperty that returns a Textbox that is defined in the page, the pagethat data is posted to (lets call it SearchResults.aspx) can accessthat property in a strongly-typed manner (no FindControl() call isnecessary) by adding the PreviousPageType directive into the top of thepage:

<%@ PreviousPageType VirtualPath="Default.aspx" %>

By adding this directive, the code in SearchResults.aspx can accessthe TextBox defined in Default.aspx in a strongly-typed manner.  Thefollowing example assumes the property defined in Default.aspx is namedSearchTextBox.

TextBox tb PreviousPage.SearchTextBox;

This code obviously only works if the previous page isDefault.aspx.  PreviousPageType also has a TypeName property as wellwhere you could define a base type that one or more pages derive fromto make this technique work with multiple pages.  You can learn more about PreviousPageType here.

6. Strongly-typed access to Master Pages controls:The PreviousPageType directive isn‘t the only one that providesstrongly-typed access to controls.  If you have public propertiesdefined in a Master Page that you‘d like to access in a strongly-typedmanner you can add the MasterType directive into a page as shown next(note that the MasterType directive also allows a TypeName to bedefined as with the PreviousPageType directive):

<%@ MasterType VirtualPath="MasterPage.master" %>

You can then access properties in the target master page from a content page by writing code like the following:

this.Master.HeaderText "Label updated using MasterType directive with VirtualPath attribute.";

You can find several other tips and tricks related to working withmaster pages including sharing master pages across IIS virtualdirectories at a previous blog post I wrote

7. Validation groups: You may have a page that hasmultiple controls and multiple buttons.  When one of the buttons isclicked you want specific validator controls to be evaluated ratherthan all of the validators defined on the page.  With ASP.NET 1.1 therewasn‘t a great way to handle this without resorting to some hack code. ASP.NET 2.0 adds a ValidationGroup property to all validator controlsand buttons (Button, LinkButton, etc.) that easily solves theproblem.  If you have a TextBox at the top of a page that has aRequiredFieldValidator next to it and a Button control, you can firethat one validator when the button is clicked by setting theValidationGroup property on the button and on theRequiredFieldValidator to the same value.  Any other validators not inthe defined ValidationGroup will be ignored when the button is clicked.Here‘s an example:

<form id="form1" runat="server">

    Search Text: 
<asp:TextBox ID="txtSearch" runat="server" /> 

    <
asp:RequiredFieldValidator ID="valSearch" runat="Server" 
      ControlToValidate
="txtSearch" ValidationGroup="SearchGroup" /> 

    <
asp:Button ID="btnSearch" runat="server" Text="Search" 
      ValidationGroup
="SearchGroup" />
    ....
    Other controls with validators and buttons defined here
</
form>

8. Finding control/variable names while typing code: This tip is a bit more related to VS.NET than to ASP.NET directly, butit‘s definitely helpful for those of you who remember the first fewcharacters of control variable name (or any variable for that matter)but can‘t remember the complete name.  It also gives me the chance tomention two great downloads from Microsoft.  First the tip though. After typing the first few characters of a control/variable name, hitCTRL + SPACEBAR and VS.NET will bring up a short list of matchingitems.  Definitely a lot easier than searching for the control/variabledefinition.  Thanks to Darryl for the tip.  For those who areinterested, Microsoft made all of the VS.NET keyboard shortcutsavailable in a nice downloadable and printable guide.  Get the C# version here and the VB.NET version here.

That‘s all for now.  There are a lot of other things that could bementioned and I‘ll try to keep this post updated.  Have agreat (simple) ASP.NET 2.0 tip or trick?  Post the details in thecomments and I‘ll add it if the content is appropriate for the list. Make sure to list your name so I can give proper credit.

For those who are interested, you can also view videos I‘ve puttogether that show how to accomplish different tasks from working withAJAX, to ASP.NET to Web Services and WCF at the following URL:

http://weblogs.asp.net/dwahlin/archive/tags/Video/default.aspx

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
使用Cross-Page Postback 页面间传值
使用Asp.net动态生成控件的使用总结! - 秋风夜狼 - sweet_chenqian...
实现无刷新DropDownList联动效果
ASP.NET页面传值的方法和一些实用技巧
ASP.NET Web 页面语法概览
.NET中获取服务器端控件的ID进行客户端编程
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服