How to pass an object from .cs to .aspx - asp.net

I am a asp .net beginner. I want to use some objects created at Site.Master.cs in Site.Master. Is there an easy way to do it?
I know how to do it in MVC(by using view(the object)). But how can i do it in normal ASP .net web application?

I don't understand what exactly you want to do.
If you want to insert some string into tag's title you can insert the following thing in SiteMaster.master file:
<img src="<%= Page.ResolveUrl("~/") %>images/logo.png">
instead of:
<img src="images/logo.png">
In the first case there will be calculated the path from the root of your application. In the second case there will be relative link. This is because server will CALCULATE the value of Page.ResolveUrl("~") function and will WRITE it in src tag.
You can do the same thing with any other methods, classes if you defined them properly. But I wouldn't recommend you to implement complicated logic in .aspx files (or .master files). Because you can end up with many difficulties with testing and styling such application.
There are other server tags:
<% %> - an embedded code block is server code that executes during the page's render phase. The code in the block can execute programming statements and call functions in the current page class. Description and examples
<%= %> - most useful for displaying single pieces of information. Description and examples
<%# %> - data binding expression syntax. Description and examples
<%$ %> - ASP.NET Expression. Description and examples
<%# %> - Directive Syntax. Description and examples
<%-- --%> - Server-Side Comments. Description and examples
<%: %> like <%= %> - But HtmlEncodes the output (new with Asp.Net 4). Description and examples
Another way: you can use JSON to send some data to the client and then process it with javascript. Take a look at this project.

If the #Page directive in your .aspx file has Inherits="XYZ" where XYZ is the class declared in your .cs file, you can simply add a protected field to your class and assign a value to it. You'll be able to access it in the .aspx file just by using its name.
You can also use HttpContext.Items property to keep objects during a single request:
HttpContext.Current.Items["SavedItem"] = "hello world";
And use it in page:
<%= ((string)Context.Items["SavedItem"]) %>

Any public or protected property or method in Site.Master.cs will be accessible from Site.Master.
but how to invoke c# code in aspx ?
There are several ways, including the <%= %> construction, and databinding syntax.
It would help if you explained what you're trying to achieve.

Related

ASP.NET Code Expression, Data Binding, and other Declarative Expressoins

What are the differences in these tags?
<%
<%#
<%=
<%$
More importantly, how do I display a page property using declarative syntax in an ASP.NET control? I'm trying to do this in an ASP.NET control. The task is to set the text of a label but I do not want to do this pro grammatically in the event I want to change the output control. I get an error about server side controls can't contain this syntax. I'm not sure that I need a databound control for what I want to do but that is another option.
Partial answer coming up.
Update
There is a new tag I've seen in ASP.NET 4.5? site
<%:
Partial answer
quoted from Mike Banavige
<% %> An embedded code block is
server code that executes during the
page's render phase. The code in the
block can execute programming
statements and call functions in the
current page class.
http://msdn2.microsoft.com/en-gb/library/ms178135(vs.80).aspx
<%= %> most useful for displaying
single pieces of information.
http://msdn2.microsoft.com/en-us/library/6dwsdcf5(VS.71).aspx
<%# %> Data Binding Expression Syntax.
http://msdn2.microsoft.com/en-us/library/bda9bbfx.aspx
<%$ %> ASP.NET Expression.
http://msdn2.microsoft.com/en-us/library/d5bd1tad.aspx
<%# %> Directive Syntax.
http://msdn2.microsoft.com/en-us/library/xz702w3e(VS.80).aspx
<%-- --%> Server-Side Comments.
http://msdn2.microsoft.com/en-US/library/4acf8afk.aspx
Update:
Okay this appears to work
<asp:Label ID="MyLabel" runat="server" Text='<%# MyProperty%>'></asp:Label>
If I use the eval syntax then I get an error about databound control or I use the <% then I get a server side controls error. Any more color appreciated.. not sure I really understand what is going on.
Perhaps it has something to do with the render phase.
Few more observations:
I can use <%= without databinding and get the property value but can not use it in a server side control without getting error.
If I use <%# in server side control but I'm required to do a Page.Databind.
Interestingly, I can use either <%= or <%# when I want to render text that is not inside a control. Although the latter requires databinding.
The new <%: syntax is explained, also called code expression syntax
With ASP.NET 4 we are introducing a new code expression syntax (<%:
%>) that renders output like <%= %> blocks do – but which also
automatically HTML encodes it before doing so.
http://weblogs.asp.net/scottgu/new-lt-gt-syntax-for-html-encoding-output-in-asp-net-4-and-asp-net-mvc-2
No, server-side controls can't. For example, I have a string property named SkinPath that give me the full App_Themes path to the current theme. I use it in the following way:
<img src='<%= SkinPath %>/Images/myImage.png' />
However, the following doesn't work:
<asp:Image ID='image' runat='server' ImageUrl='<%= SkinPath %>/Images/myImage.png' />
Instead, it renders the src literally in the result <img>.

ASP.Net <%# %> and <%= %> rules?

Can someone explain to me the rules around what can and cannot be evaluated/inserted into markup using the <%# %> and <%= %> tags in asp.net?
When I first discovered I could inject code-behind variables into mark-up using <%= I thought 'great'. Then I discovered that if such tags are present you can then not add to the controls collection of the page (that's a whole different question!). But <%# tags are ok.
Is there a way I can inject a code-behind variable or function evaluation into the page using <%# ? Thanks.
<%%> are code blocks. You can put any server side code in them. This is a shortcut for <script runat="server"></script>.
<%=%> is for outputting strings. This is a shortcut for <script runat="server">Response.Write()</script>.
See here for more detail about <%%> and <%=%>.
<%#%> are used for data binding expressions.
See the index page for asp.net Page syntax.
The <%# inline tag is used for data binding, so if you want to use a code-behind variable inside it, you will have to bind the page or control the variable resides in:
Page.DataBind();
You can include this statement in the Page_Load or Page_PreRender event.
See this article for more information about the use of inline tags in ASP.Net, and this article for more about server-side databinding.

Inline scripting in ASP.NET

I want to learn advanced and basic things about ASP.NET inline scripting like
<img src="<%= Page.ResolveUrl("~")%>Images/Logo.gif"/>
or
<asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'></asp:Label>
And so on...
And, what's the difference between <% %> and <%# %> and such stuff?
Where can I find from basic to advanced implementation of those usages?
Check out this article for the specifics of the different inline tag options.
From the article:
<% ... %> -- The most basic inline tag,
basically runs normal code:
<%= ... %> -- Used for small chunks of
information, usually from objects and
single pieces of information
like a single string or int variable:
<%# ... %> -- Used for Binding Expressions;
such as Eval and Bind, most often
found in data controls like GridView,
Repeater, etc.:
<%$ ... %> -- Used for expressions, not code;
often seen with DataSources:
<%# ... %> -- This is for directive syntax;
basically the stuff you see at the top
your your aspx pages like control
registration and page declaration:
<%-- ... %> -- This is a server side comment,
stuff you don't want anyone without
code access to see:
In general, <%#..%> is used for preprocessing a template, such as when databinding, whereby the names of properties of the objects are not known at compile-time. If, for example, you have an ASP.NET Repeater object, and you databind a list of objects to it, this notation is used to pre-populate values that could not be set at any point except during the databind lifecycle.
The other notations, <%..%> and <%=..%> are more standard and you'll see these far more often than the other syntax previously discussed, especially if you use something like ASP.NET MVC instead of ASP.NET Web Forms. The syntax <%..%> executes arbitrary script inline, and nothing more, but allows you to write entire blocks of .NET code such as if statements, while loops, for loops, etc. The syntax <%=..%> is an evaluate-and-write syntax, and is rough equivalent of <% Response.Write([..].ToString()) %>. I.e., <%= myVal %> is the same as <% Response.Write(myVal.ToString()) %>
These syntaxes are basic ASP.NET knowledge.

Simple HTML construction in ASP.NET?

A simple question, I think:
I want to put a tag into an ASP.NET app I've been asked to maintain, so I'm coming at this from a newbie point of view just tinkering around the edges without knowing a lot.
I wrote an old ASP application back in 1998, so I am just running on memory...
How do I write some output to the webpage?
I know I can use an
<asp:label id="blah">
but then I need to define a Label blah; in my code behind and then assign it.
I believe that I can put in-place:
<% Response.Write("sometext"); %>
and that will write sometext in the location within the page. (Am I correct?)
Lastly, I remember there was a syntax to the effect of
<%= "some string" %>
but I can't find the documentation on it, to say either it is deprecated, unadvised, or the rationale for such a decision.
I have tried googling for "ASP.NET grammar" but I can't even find a good description that "<%=" even exists, though it is mentioned in a few blogs.
For something simple, like inject the global version number, or the current date, then I can't see anything particularly wrong with in-place composition - it would save me defining 15 labels and having to initialise them all - though perhaps the asp:label approach could reference one global instance of a label?
Just asking for opinions on good practices :)
<%= string %> is perfectly valid ASP.NET syntax. The reason you will often find references to problems with using that is people use <%= (equivalent to Response.Write) when they should use <%# (for databinding) or vice-versa.
For example, we use it very extensively in our content managed site, where we pull in values from a global settings repository:
<%= SiteContext.Current.GetSetting("SiteTitle") %>
MSDN:
MSDN entry on <%= (this is under the JScript.NET section but still applies)
MSDN entry on <%#
Some others suggest <%= is not a "best practice" or a very good approach, but I strongly disagree with that sentiment. For an MVC-ish type site (especially a site that is template- or view-driven in some way), the most direct approach is frequently more effective than using server controls.
Just be mindful that when you use an <asp:Label /> it renders the .Text inside the <span> tag whereas an <asp:Literal /> adds no extraneous HTML to the string passed to it.
For example, if you were building a content management system and wanted to display user-driven HTML, a Label control would not correctly display the output from a WYSIWYG type rich textbox whereas a Literal control is the appropriate choice.
The <%= %> is the late-bound equivalent of the Literal's .Text property. The only difference here is when the value is placed in the page (aside from obvious syntax and separation of concerns paradigm) during the course of the page lifecycle.
Since the .Text property is on a control inherited from WebControl, it can be set/read/manipulated during any of the events following the control's Load event (wherever/whenever you load the control inside the page), but the <%= %> text cannot be directly read/used/manipulated by the code-behind without referencing some other control to get to it (like a containing div's InnerHtml property).
There are lots of options. You could use a single label, and string concatenate all the data you want displayed in that location.
You could create a user control with the layout you want and assign values that way.
You could inject it directly with response.write or the <%= %> syntax
You could create an HtmlGenericControl in your code behind (it's a div), add some text to it, and inject it into the pages controls collection.
Whatever you pick, try and go with the existing style of the coded page.
Look up the term "render blocks" for the <% %> syntax.
How about using
<asp:Literal id="z" text="goofy" runat="server" />?
Labels are usually used with forms.
You can also take full control of the rendering of your pages and controls and compose whatever you need to. You control the HTML, the order of rendering your controls, etc...
Go with the <asp:label /> (or a literal control if you want to customize some html in the content). Seriously. I'ts not that hard: when you put label in your markup visual studio will create it in the code-behind for you, so there's no extra work involved.
You could use the <%= "some string" %> syntax in web forms, but there can be issues when mixing that with the asp controls and there's a good reason new frameworks moved away from mixing logic like that in with your markup.

Strongly-typed ASCX in WebForms 3.5?

I'm looking to get rid of the code-behind for a control in my WebForms 3.5 application. Again bitten by the bug of how it's done in MVC, I'd like to get a step closer to this methodology by doing:
<%# Control Language="C#" Inherits="Core.DataTemplate<Models.NewsArticle>" %>
This gives me the parser error you'd expect, so I remembered back to when this was an issue awaiting a fix in the MVC Preview, and changed it to:
<%# Control Language="C#" Inherits="Core.DataTemplate`1[[Models.NewsArticle]]" %>
But this doesn't work either! How is it that the MVC team were able to harness this ability? Was it something special about the MVC project type rather than the latest VS2008 Service Pack?
Short of giving up and requiring future templates to have code-behind files, what are my best options to get this as close to the generic user control method as possible?
Well, it appears like I've managed to do it. After looking at the PageParserFilter implemented by the MVC team for ViewUserControl<T>, I was able to construct something similar for my own DataTemplate<T> purposes. Sweet. I can now use the line:
<%# Control Language="C#" Inherits="Core.DataTemplate<Models.NewsArticle>" %>
And, without any code behind file, it parses! I'll report back if I find that I've broken something else in the process!
With WebForms you lose pretty much everything that makes them useful without a code behind page, because then VS can't auto generate the designer file that holds the actual definitions for all your runat="server" controls.
What you can do is have a common base page class, and make that generic:
public class DataTemplate<T> : Page {
public T Model {get;set;}
}
public partial class MyCodeBehindClass :
DataTemplate<Models.NewsArticle> {
...
}
This would allow all the drag-drop component stuff that WebForms does to work unhindered, while also allowing you to access a strongly typed model on the page:
<%# Control Language="C#" Inherits="MyCodeBehindClass" %>
<% foreach( var item in Model ) { %>
<!-- do stuff -->
<% } %>

Resources