ASP.NET equivalent of server side includes - asp.net

Although the classic ASP method of server-side includes works in ASP.NET, I get the impression it is not the preferred method. How am I "supposed" to be achieving the same effect?
This is how I'm doing it at the moment:
<!-- #include file ="functionlib.aspx" -->

You now have a number of options that provide this effect, but in a different manner.
User Controls (.ascx)
Master Pages (.master)
Server Side Controls (.dll)
Class Libraries (.dll)
App_Code Classes (.cs/.vb)
Each are used for differently to achieve different things. It depends what you're really trying to do. Given the name of your include file, I'd imagine you're trying to include library functions that will be used within the context of your page.
Consequently you'd write a class library that contains the methods and import them into your application/aspx.
If you're looking at templating a page that will do most of the layout work to provide a body for differing content then you'll be interested in Master Pages.
If you're looking at templating controls that can be used in many pages, then you're going to be after User Controls.
If you're looking at templating controls that can be used by many users across many projects, then you'll be looking at Server Side Controls.
If you're looking at a library of classes/methods then you'll develop a class library or use an app_code class which can be JIT compiled the first time it's called. This could at a stretch be considered more like classic ASP, but really it functions more like a class from a class library as a single unit. You can call it from within your codebehind or within <% %> tags in your aspx/ascx code without requiring a reference to a class library.
We don't really use "includes" per se any more, but each of these tools in your toolkit allow you to provide similar concepts for different scenarios. As a developer you will interact with the entire page lifecycle of your web pages differently. ASP.NET is a very different beast than classic ASP. It truly takes a different view/approach and will take some amount of patience to figure out the differences.

How about <% Response.WriteFile("myFile.aspx"); %>?
See: https://support.microsoft.com/en-us/help/306575/how-to-dynamically-include-files-in-asp-net

If you'e using ASP.NET MVC then Html.RenderPartial is your friend here.
http://msdn.microsoft.com/en-us/library/system.web.mvc.html.renderpartialextensions.renderpartial.aspx
A partial view can be implemented as a .ascx or an .aspx and putting the above call in your "primary" page basically says "get the output from this partial view and render it here".
Parial views can make use of the ViewData that your primary view received from the controller.

Sounds like what you need to be looking at is the entire concept of MasterPages.
Unless you are looking at just importing functions and other utilities (not html content). If that is the case (and you are using the code-behind model), you should just be able to include the appropriate file or namespace using the imports command at the top of your .vb page (adjust accordingly for C#).

Related

Reusing ASP.NET code in multiple pages

Is there a way to reuse a piece of ASP.NET code (that tag-based code, not the code-behind) in many different pages? For example I have a <div> with some contents in it that appears in 5 different pages of my site. I'm looking for a technique through which I could save this <div> in a separate web-content file so to speak, with maybe a different extension like MyDiv.ASPC and could then do a server-side tag anywhere in a webpage like:
<asp:Import href="~/MyDiv.aspc" />
and ASP.NET would inject the entire content of this file at that point where this tag appears.
I thought of creating a user control for this, but I'm not sure if a user control always injects precisely what is written in its body, or could there sometimes be unwanted tags generated by user control itself.
Or are there existing better ways of doing this?
Edit
About Master Pages, they are far away from what I'm looking for. They are actually good for a common basic layout of your website. My idea is quite opposite of that. My pages do not have a common layout; it is just that they have one common <div>. It is more closely fulfilled by a UserControl.
For UCs, my fear is that they generate more than what is written in their body, whereas what I'm after is a simple text injection. To put it technically, what I'm looking for is basically a preprocessor step (kind of #include thing in C++) rather than a compiler step, if you see what I mean.
You need to use ASP.NET User Controls, as these are specifically created to be the solution to the problem you are describing. For more information, see MS Documentation.
From their documentation...
In addition to using Web server controls in your ASP.NET Web pages,
you can create your own custom, reusable controls using the same
techniques you use for creating ASP.NET Web pages. These controls are
called user controls.
A user control is a kind of composite control that works much like an
ASP.NET Web page—you can add existing Web server controls and markup
to a user control, and define properties and methods for the control.
You can then embed them in ASP.NET Web pages, where they act as a
unit.
An empty userControl would do just that - nothing. A user Control just adds it's contents to the page, or usercontrol hosting it. It adds nothing extra.
UserControls give you a nice easy page fragment type approach to reusing content. They work great within a project & most people use them for just that.
If you wanted to make something more reusable across projects, you could write server control. It's more involved, but much more reusable. Google should be able to find you many tutorials on how to do this.
Ran a short test. User Controls do not enter extra tags as long as you don't place any Runat="Server" tags in it, so this would indeed be a solution I guess.
You can also read output from a cache object where you would read your files.
So
<%= Static.ContentXyz %>
would mean:
public static class Static
{
public static string ContentXyz
{
get
{
string s;
if (!this.cacheDictionary.TryGetValue("ContentXyz", out s))
{
s = File.ReadAllText(Server.MapPath("ContentXyz.html"));
this.cacheDictionary("ContentXyz", s);
}
return s;
}
}
}

Webparts asp.net

What are the disadvantages to using webparts in asp.net? Are they losing their popularity?
I was planning on creating a user defined Dashboard and was thinking of using Webparts, is this the way to go or is there another way of doing customisable dashboards these days? I would prefer not to have to use a 3rd party product.
To me, webparts are more of a sharepoint thing these days.
Other than that, with some design you can get all you need with user controls and some classes of your own to get common functionality and layout sorted out.
Say you have a base class called DashboardWidget that inherits from WebControl here you could define a overridable method
ProcessDataSource -> executes a query to a database or service and formats the results for presentation
And in the prerender method (or something similar along the asp.net lifecycle) you call ProcessDataSource (you could use the DataSource property most controls already have).
Then you inherit from DashboardWidget to make your controls and in the render method you override ProcessDataSource to get the info the way you need and the Render method to setup what to display.
Ideally you should define your own data source class to have a single place to define where to connect, how, credentials, etc..
As for the layout, newer versions of asp.net include several layout option you may use (and there is always pure html if you want)
I'm shooting from the hip a bit here, but that's a way to do it without involving webparts, that to me, are not that popular outside of sharepoint.
Hope anything of this helps

How to Consume a Custom Server Control

I seem to be having a lot of trouble with this.
I want to create an ASP.NET control that implements some core logic, and then I want to be able to derive several controls from that, which each implement their own specialized logic.
I started with a User Control, but I couldn't find a way to derive from it. I tried setting the Inherits attribute in the derived control but, no matter what I did, the derived control just didn't seem able to recognize the base control.
So then I tried a custom server side control by using a regular class that inherits from Control. (Note that all my rendering is done from code.) But I can't seem to find any way to get a page to recognize the control. I've tried different syntax in the #Register directive but either it tells me the src attribute is missing or it just can't find the control. (Note that I prefer not to create a separate assembly if I don't have to.) I have no idea what to put as the assembly if the control is from the current assembly.
Can anyone make suggestions on this? Any examples that would work for my configuration, or perhaps a different approach entirely?
Note that I am not currently using page/control code-behind. All my page scripting is stored in the same file as my markup.
In fact, despite various error messages about missing attributes in the #Register directive, I found it works just fine if I reduce the number of attributes in this directive to just tagprefix and namespace.

why not user control?

why should be used use control template in asp.net? please, someone say me.
Can anyone tell me why I should use a Control Template over a UserControl in ASP.Net?
If you're familiar with MVC, a User Control is like the WebForms equivalent of a partial view.
Update (when I answered, the question asked when to use a User Control...):
A server control is appropriate when you want to bundle assets and functionality for wider distribution than a single project. It is more complex to develop a server control than it is a User Control, but a server-control allows you to completely encapsulate HTML, CSS, JavaScript, images, and server-side logic within a single DLL.
Conversely, a User Control is much easier to develop, but cannot contain assets such as external CSS/JS or images. User Controls are basically just partial bits of an ASPX page.
Unless you know that you need the features of a server control, I would always recommend a User Control for simple de-duplication of content that's repeated in multiple ASPX pages.
A User Control enables you to create your own custom control modules. They're useful because they are reusable, meaning you don't have to duplicate a lot of code. You can embed them in ASP.net pages, and you can define methods and properties for them.

What is the unit of reusability in .NET MVC apps?

In traditional ASP.NET Web Form applications, UserControls are a great way to encapsulate functionality so that it can be reused. However, UserControls don't fit well into the MVC model. They often make heavy use of ViewState and they blur the seperation of concerns that MVC promotes.
My question is, how do you best bundle a piece of functionality so it can be shared across MVC applications?
As an example, consider a from/to date-selector UserControl that:
allows a user to select two dates, either using a javascript overlay or by typing in day, month and year into seperate fields
can be configured to default to either today and tomorrow's dates or to dates of the developer's choosing
validates the dates that comes back from the user to ensure the from date is before the to date
exposes From and To properties that can be accessed by code-behind
How would I best build something like this in .NET MVC so that I can easily reuse it?
Note that to fully emulate User Control's functionality the MVC component would have to manage the submitted form data and validation - not just the presentation.
In general I would agree that user controls are nice in terms of encapsulating UI stuff, but I don't think too much has really changed in MVC. If I remember right re-using user controls across classic Asp.net projects was a pain and was never really the best way to truly create reusable components. Most UI toolkits that you bought for classic ASP.net didn't give you user controls, they gave you essentially server controls and javascript controls.
In your example, I would probably create or find a jquery (or ur framework of choice) plugin that did what you wanted on the client side. You could also build a C# wrapper around it similar to what Telerik did with some of the jquery UI controls. I do think that the word code-behind and even viewstate will disappear from your vocabulary the more you get into MVC.
If you look at what open source projects are out there for MVC you will get your answer in terms of what you should be doing.
The MVC Contrib app adds a lot of features by creating extension methods and helpers. Their grid control is a typical way to create a reusable component that you could use across projects
Telerik, created some extensions that wrap jquery controls and do asset management.
Finally I think if you look to the future, MVC has areas, which if I interpret it right will give you the ability to break your project apart into multiple smaller projects.
Besides what is already suggested, ASP.NET MVC v2 will have generic templated input controls, see here. You can read how other people do similar techniques, for example, here:
We have
exactly 1 method call for generating a
form element, “Html.InputFor”. As
part of that “InputFor”, it examines
an input specification, that collects
the PropertyInfo, any attributes, the
type, any modifiers called, and
selects an appropriate InputBuilder.
Call InputFor(p => p.Id) and Id is a
GUID? That creates a hidden input
element. Call InputFor(p =>
p.Customer.Address) and Address is a
complex type? That looks for a
partial with the same name of the type
Having considered the helpful answers from others, I will have a go at answering my own question.
It seems to me that the key difficulty with emulating UserControls in MVC is that they crosscut the concerns that MVC aims to seperate. The from/to date selector UserControl in my example incorporates elements of Model, View, Control and interation. UserControls' ability to bundle all this together is exactly the reason that they don't fit well into MVC.
That means that to create a psuedo-UserControl in MVC requires four seperate pieces:
A Model class - in this case an Interval class or similar
A PartialView that knows how to render the Model to HTML
A jQuery script to layer interactivity on top of the PartialView's HTML
A ModelBinder that can deserialise postdata into an instance of the Model class.
The ModelBinder is important because it deals with data coming back from the user. Without it, every Controller that wanted to display a to/from date selector in any of its Views would have to know how to assemble the six postdata fields - and how to cope if they were invalid or some were missing.
Two ways that I can think of. A partial view though this doesn't really transfer well from app to app because you are moving around ascx files. Not a big pain but not my flavour.
I prefer to use WebControls. They are super easy in mvc and all you need to do is reference the library in the project and possibly in your config file and there you go.
I think some of the answers have missed out on the postback functionality of controls. One way you could handle that is to pass any generic information via ViewData when rendering your partial view. That could then post back to its own control, which in turn could redirect to the UrlReferrer.
Its a little messy and use of UrlReferrer poses a security risk. But it is one way around the problem
You can create a jQuery plugin.
As user-controls provided in ASP.NET Webforms, MVC provide a lot of ways to make the controls and code that can be reused in other app.
Using Partials If your partial code have some C# logic and render the html using Razor/aspx code then it's bst to maintain them in razor file.
Write JavaScript Functionality as plugin If you maintain your code and write it as better as it can be used in other app then it would be a huge advantage for you. Next time when you work on other app just open this solution copy it and modify it. Write JavaScript code that can be used as plugin maybe take some more brainstorming.
Write Code As a Separate C# library If some code is too common for every app you make.for example you write a member authentication system or some global function (C#) that are used in every app you made then maintain them in a separate solution so it can be used in other app you made whenever you trying to make a new app in future.

Resources