Tuesday, March 13, 2012

Should an .aspx Web Page be in a Namespace?

Hi ... new guy here ...

I've used Namespaces with simple C# console applications. Works pretty good.

I'm now creating just a simple default.aspx Web page. I was wondering if the normal practice is to supply the Web page with a Namespace in some fashion in the default.aspx.cs code. I have not had luck compiling, with one, but I wanted to make sure.

Thanks!

DB

Something like this:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web; ... etc ...
using System.Data.SqlClient;
using System.Data.Common;
namespace MyNamespace
{

public partial class _Default : System.Web.UI.Page
{

Etc...

} // Class

} // Namespace MyNamespace

You can do so! If you have several features on your website, you can group each feature of pages using Namespaces!

Does this help?


I can only speak for myself but you tend not to see people defining namespaces for asp.net web pages - that's not to say that you wouldn't want to, it just doesn't seem that common.

What I can say is that if you have any code files in the App_Code directory of your ASP.NET site then you should give these classes a namespace - this is a guideline (code analysis).

HTH.


I don't see any real use of using namespaces in the webforms and I think that's the reason why these were omitted from the VS 2005 default Website model. Anyways here is a nice post on the same topic which discusses the same :

http://odetocode.com/Blogs/scott/archive/2006/02/07/2849.aspx

Hope this helps,

Vivek


Thanks everyone for the great responses!

I'm thinking I want to add a namespace to the code behind for my default.aspx Web form. I'm using the format in the example above, but I'm getting several compiler errors including:

"Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class." If I pull the Namespace { } out the problem goes away.

Is there anything obviously wrong with the above?

While we're at it ... I was wondering about doing the same thing with a Web Service. Any tips here?

Thanks!!!


 Hi,

"Is there anything obviously wrong with the above?" --> unfortunately, I don't think there is anything wrong in your former code:

Something likethis:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web; ... etc ...
using System.Data.SqlClient;
using System.Data.Common;
namespace MyNamespace
{

public partialclass _Default : System.Web.UI.Page
{

Etc...

}// Class

}// Namespace MyNamespace

I think you can create your own namespace as you like(butMAKE SUREyou have made the corresponding change within the Page MarkUP(the aspx file) )

< @. Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Your Nampespace.class_Default" %>

I guess the WebService should be the same. Hope my suggestion helps :)


0 comments:

Post a Comment