Possible to do inline code in ASPX markup? - c#

Is it possible to do things in a PHPish way in ASP.Net? I've seen <%= %> but I've tried it and couldn't get it to work.
The PHPish equivalent of what I want to do is
<script src="<?php echo ResolveUrl("jquery/js/jquery.js"); ?>"></script>

Yes, it's quite possible. You should familiarize yourself with all the variations of the (so called) alligator tags though.
Put code in between <% %> blocks. The <%= %> variant is a shortcut for Response.Write, and is used as a shortcut for directly outputting a variable to the page.
The following should work, as long as ResolveUrl is returning a string. Notice there is no ";" to end the line though.
<script src="<%= ResolveUrl("jquery/js/jquery.js") %>"></script>

Related

get current user Asp. Net C#

Is there is a way to get the current user in the aspx page,the page with the html definitions? (i know how to get it in the aspx.cs page)
This should work:
<%= Page.User.Identity.Name %>
Page.User Property
Use the following code block in the aspx where you want it to show up.
<%= System.Environment.UserName %>
See ASP.NET "special" tags for more info.
Use code tags
<%= YourMethodToGetTheCurrentUser() %>
You can access any public or protected variable from the code-behind file in it's .aspx file by wrapping your code in these characters:
<% if(PublicObject.Property > 0) { %>
<p>You can write normal HTML, or write strings like this: <%= PublicObject.Property %></p>
<% } %>
<% %> let's you add logic or commands into a page. You can use this to add for loops or if statements. <%= %> is used to write content directly to the page. This is used to print the contents of a variable.
<%= System.Web.HttpContext.Current.User.Identity.Name%>
Yet another one:
<%= HttpContext.Current.User.Identity.Name %>

Angle Brackets in Page head element

Iam new to ASP.NET with prev. PHP experience (which meaby is causing this problem) and Iam having small problem passing data from codebehind to view-source.
I declared string variable on codebehind side such as:
...
public string mystring = "Scotty";
protected void Page_Load(object sender, EventArgs e)
{
...
So now I want to use it in view-code but when I put it in angle brackets (<%: or <%=) and put it in head element I got no access to this value. On the other hand when I put it in BODY element everything is ok.
My failing example (simplified):
<head runat="server">
<script language="javascript">
function beamMeUp()
{
alert(<%=mystring;%>);
}
</script>
</head>
<body>
<input type="button" onclick="javascript:beamMeUp" value="Warp6" />
</body>
Can anyone explain it to me why I can't use it (the <%=mystring;%>) in HEAD but i can use it in BODY ?
Best regards
The semicolon isn't necessary when using <%=. Think of it as writing:
<% Response.Write(mystring); %>
You will want to wrap that in quotes as well.
alert("<%=mystring %>");
Without quotes would be: alert(Scotty);
which does not make much sense unless you have a javascript variable called Scotty.
It should give you an alert box showing undefined
The code-behind variable mystring is available in the <head>. C# IntelliSense isn't displaying for it since it's inside of a <script> tag.
Your problem may be that you have
<head runat="server">...
I believe this causes ASP .NET to construct an HtmlHead object which you can reference from Page.Head. However, you cannot have inline constructs such as <% .. %> and <%= %> when doing this. I believe this is also true of other ASP .NET controls such as
<asp:TreeView ...>
<asp:TreeViewItem> <%= will cause error! %> </asp:TreeViewItem
</asp:TreeView>
http://geekswithblogs.net/mnf/archive/2007/11/14/code-render-blocks-not-always-work-inside-server-controls.aspx
You really had three problems:
1.) You have a javascript error as pointed out by the first responder when he told you to use:
alert("<%=mystring %>");
2.) You have an ASP .NET error because you can't use <%= %> inside a tag that has runat="server".
3.) Another javascript error in your onclick assignment. Note it is better to wire up events in code using attachEvent and addEventListener. Your onclick assignment does not need the javascript: in front. You might do this for an href attribute, but not an onclick. In the onclick, you are already executing javascript. You could have onclick="alert('yo!')" which would work. Also, when executing a function, you must include the parenthesis, so you should have onclick="beamMeUp();" (semi colon optional).
Your revised code should look more like:
<head> <!-- notice runat="server" has been removed -->
<script type="text/javascript">
function beamMeUp()
{
alert("<%=mystring;%>");
}
</script>
</head>
<body>
<input type="button" onclick="beamMeUp();" value="Warp6" />
</body>
Note: I tried the code above and it works. I made these changes
removed runat="server" from the <head> tag
added double quotes to alert("<%=mystring;%>");
changed onclick event to onclick="beamMeUp();" NOT onclick="javascript:beamMeUp".
Good luck.

List of what each of <% means (<%#, <%=, etc...) [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
ASP.NET “special” tags
You know how you can embed property value from code-behind in your page by simply using <%= PropertyFromCodeBehind %> in your .aspx?
Well, I only recently discovered that and I can't seem to find any tutorial that would explain this (and related stuff) in more depth (I only know that <%# is used in conjuction with Eval) - probably because I'm using <% for searches.
So, can anybody provide me with more detail explanation of these tags, or give a link to some tutorial that explains all this? I'm interested in anything that can be learned on this subject; somewhere I saw that you can do fancy stuff like <% for ... %>.
Here is a good place to get started.
There are several different syntaxes:
<%$ %> Expression Syntax
<%# %> Data-Binding syntax
<% %> Evaluated Code Blocks
<%= %> Statement and Expression
New to ASP.NET 4 is the HTML encoding syntax (haacked). This is the same as <%= %> except the result is HTML encoded (for non IHtmlString types). The new syntax is intended to replace <%= %>.
<%: %> HTML Encoded output
See ScottGU's post post to get you started.

Trying to save output from RenderPartial to a Javascript variable and use it later

In my Create View:
<script type="text/javascript">
var tabContent = "<% Html.RenderPartial("ProductEdit", new Web.Model.Product()); %>";
</script>
Unfortunately this seems to break. At least the quotes (") aren't escaped (\"). How could I "inject" the results of RenderPartial into JS?
Instead of storing it as a variable, you can just put it in a placeholder, like this:
<div id="tabContent" style="display: none;">
<% Html.RenderPartial("ProductEdit", new Web.Model.Product()); %>
</div>
Then when you want to use it, get it via .innerHTML, like this:
var myVar = document.getElementById('tabContent').innerHTML;
This is useful in other scenarios, if you want to clone it, etc...it all depends how you intend to use it, but I've found this a much more useful approach in most cases.
Maybe using '<% Html.RenderPartial("ProductEdit", new Web.Model.Product()); %>' will help?

Saving js file with c# commands

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="../../Content/css/layout.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Areas/CMS/Content/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/Areas/CMS/Content/js/jquery.jeditable.js"></script>
<script type="text/javascript" src="/Areas/CMS/Content/js/jeditable.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".naslov_vijesti").editable('<%=Url.Action("UpdateSettings","Article") %>', {
submit: 'ok',
submitdata: {field: "Title"},
cancel: 'cancel',
cssclass: 'editable',
width: '99%',
placeholder: 'emtpy',
indicator: "<img src='../../Content/img/indicator.gif'/>"
});
});
</script>
</head>
This is head tag of site.master file. I would like to remove this multiline part from head and place it in jeditable.js file, which is now empty. If I do copy/paste, then <% %> part won't be executed. In PHP I would save js file as jeditable.js.php and server would compile code that is in <?php ?> tag. Any ideas how to solve this problem?
Thanks in advance,
Ile
In PHP I would save js file as jeditable.js.php and server would compile code that is in tag.
One thing to keep in mind here is that php is now forced to process that entire javascript file on every request. This is generally a "Bad Thing"TM, and it uses up server resources that could be spend elsewhere.
As Raj Kimal's answer already mentioned, what we do in ASP.Net to handle this in the most efficient way possible is have a short script defined inline with the page that does nothing but assign result of server code to variables. Do this before declaring other scripts, and you can then use these variables in those scripts directly. That way, you don't have to do any extra server work for your external javascript files.
I'll make one addition to Mr Kimal's answer. It's often best to enclose these variables in an object, to help avoid naming collisions. Something like this:
<head runat="server">
<script language="javascript">
var ServerCreated = {
ArticleAction:'<%=Url.Action("UpdateSettings","Article") %>',
OtherVar:'some server data'
}
</script>
</head>
Then your jeditable.js file would look like this:
$(document).ready(function() {
$(".naslov_vijesti").editable(ServerCreated.ArticleAction, {
submit: 'ok',
submitdata: {field: "Title"},
cancel: 'cancel',
cssclass: 'editable',
width: '99%',
placeholder: 'emtpy',
indicator: "<img src='../../Content/img/indicator.gif'/>"
});
});
Define your variable part as a js variable.
var foo = '<%=Url.Action("UpdateSettings","Article") %>';
and place it before the js reference. Then use the varible in your js file.
You can put the script inside an .aspx file and set the content type to text/javascript in the #page directive. You will still be able to use the code tags.
The cost of processing the entire javascript file every request can easily be mitigated by applying server side caching so that shouldn't be a problem. This can be configured in the #page directive as well.
You have a few options, but the key here is that if you need to use the <% %> syntax to get information you need to be in the context of an ASP.NET page.
You "could" move the actual function to an external file, and reference the JS, then add a small inline script block that called the function with two parameters, but that defeats the purpose of what you want.
The real question here, why have the overhead of an additional HTTP request for a single method?

Categories