In Razor I can do this:
<p #Html.MyCustomDataAttributeFor(person) >#person.Name</p>
To render something like this:
<p data-custom-person-id="1234567890" >Fred</p>
Must I really then do this in (unobtrusive) JavaScript:
$('p[data-custom-person-id="1234567890"]').css('background-color','red');
When I'd prefer to do this:
$('p[#Html.MyCustomDataAttributeFor(person)]').css('background-color','red');
If only I could, otherwise should the data attribute generated by the HTML helper change, my client side code will no longer style the element.
Could you point the script to a .cshtml-file?
<script type="text/javascript" src="/myscript.cshtml"></script>
I think I've done this for both .php and .aspx so I don't see a reason it shouldn't work.
In those cases it makes the server first process the file.
Otherwise you could use a customer HttpHandler that parses whatever text you want server-side before it's sent to the client.
The easiest however, would be to set some Javascript variables from Razor, ie:
<script type="text/javascript">
var customerId = '#Html.MyCustomDataAttributeFor(person)';
</script>
And then write:
$('p[' + customerId + ']').css('background-color','red');
data-custom-person-id="1234567890" is rendered to the browser after server has converted #Html.MyCustomDataAttributeFor(person) to that value. On the client side you will not be receiving these text at all. So, you cannot use those statements for client side styling.
Related
I have a webform called "Home.aspx".
In Home.aspx.cs, I created an array called myArray.
I want to use this array in Home.aspx to generate a word cloud.
something like below:
<script>
$('#wordcloud').jQCloud(myArray,{shape: 'rectangular'});
</script>
Can someone help me in solving this.
First, you don't want to put the C#-generated array onto your aspx page, because that array is a C# object, and javascript needs to be sent as text. You want to put a string output of the array onto the page. So you should create a string as a protected property in your code behind, and put the string of the array into that.
Then, on the front end, you can write the protected property onto the page with <%= myString %>
There are a couple of ways to achieve it.
Let server side code generate the whole JavaScript for you, which
means you will need to construct the JS code as a string in the
code-behind (.aspx.cs page) then use
ClientScriptManager.RegisterStartupScript method to register it so
that JS code will be executed when page loads.
Use server side script tag on your ASPX page. It's like point 1 but you write server side code on your front page.
Apply JS serialization and let the serialiser generate the JS array for you.
Below is an example of using a serialization approach.
<%
// create you array here
var myArray= new string[]{"apple", "orange"};
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
%>
Then what you need is to place above code on your ASPX page, before your JavaScript code block.
<script>
var myJsArray = <%= serializer.Serialize(myArray) %>;
$('#wordcloud').jQCloud(myJsArray, {shape: 'rectangular'});
</script>
One thing to remember though, the server side array object and client side javascript array are two different things. The serialization/deserialization is required to allow data/array of data to be passed between browser and web server.
Within my C# code behind page, I have the following:
MembershipUser currentUser = Membership.GetUser(false);
HttpContext.Current.Session["UserGuidAsString"] = currentUser.ProviderUserKey.ToString();
At the bottom of the corresponding ASPX page, I have the following code:
</form>
<script type="text/javascript"> var userGuidAsString = '<%=Session["UserGuidAsString"]%>';
alert(userGuidAsString);
</script>
</body>
</html>
It gives the proper expected result which is an alert box with the User's GUID when I run the page
I wanted to move the JavaScript code to a .js file so that the code is more modularized and organized.
I created the following test.js javascript file with the following contents:
var userGuidAsString = '<%=Session["UserGuidAsString"]%>';
alert(userGuidAsString);
I also modified the ASPX page so that it would include the test.js javascript file:
</form>
<script src="/Scripts/test.js" type="text/javascript"></script>
</script>
</body>
</html>
It fails because it just gives an alert box with
'<%=Session["UserGuidAsString"]%>'
as a message
May I please know how I can make in line server C# code work within JavaScript .js files?
By This your accessing Server Variable
'<%=Session["UserGuidAsString"]%>'
its not functionlity of Javascript.
You can write this code without js block also..
its like ASP code..
so its workg with .aspx page only not in javascript
A common workaround for this is to put the server variable in an html hidden element. For example:
<input type="hidden" id='guid' value='<%=Session["UserGuidAsString"]%>' />
Then your javascript file:
var guid = document.getElementById("guid").value;
Or, you could define a js variable in your html, and reference that in your js file. Just make sure to declare the variable before you reference it.
<script type="text/javascript">
var guid = '<%=Session["UserGuidAsString"]%>';
</script>
<script type="text/javascript" src="yourScript.js></script>
Then in your js file you can simply use the guid variable.
In order for C# to get executed on the server before the .js file reaches the client, you'd have to register that page extension in IIS so that the asp_net .dll processes .js files.
In your particular case (handling GUIDs), you really don't want to go this route, because with the nature of .js file caching, you're going to have a lot of problems ensuring that it's a fresh version being served up every time.
I suggest recreating a very simple (and yes, modular/reusable) JS function that makes a call to, say, GetUserGuidAsString.aspx by using AJAX or the equivalent.
I have two columns of data in an Database on MS SQL Server. One is datetime variable and another is an int.
Im trying jQuery and Flot to plot the datetime vs int.
I can programatically get the data from SQL Server using C#. But how do I pass it to the JavaScript File which has the vars for flot?
If you want to call a script in a loaded html document, you can use the Invoke method from the appropriate HtmlDocument or WebBrowser object to call a javascript function within that page, for example:
http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.invokescript.aspx
I am unsure how you would pass the data from c# to a *.js file in your case, I dont think its possible. But you could try a hack on the page that contains the *.js include you could try declaring and setting the javascript variable to the c# code (so in the ASPX, if its ASP.NET) and then putting the *.js include reference after that point and in it not re-declaring the variable but using it. You can also use JSON or AJAX to call server side code and return values and execute code.
Scenario 1: (The hack way, which is not clean and hard to maintain but does the job)
File.aspx
<script language="javascript" type="text/javascript">
var MyVariable = "<%=C_Variable_On_Code_Behind%>";
</script>
<script type="text/javascript" src="/scripts/YourJsFile.js" >
</script>
YourJsFile.js
if(MyVariable != null && MyVariable.length > 0){
//Do some thing.
}
Scenario 2: (JSON, AJAX, JQUERY UI)
jquery ui sample for a autocomplete: try this link
Another example: Or this link
Scenario 3: (Writing to the client from server-side c#)
Use RegisterStartupScript or RegisterClientScriptBlock via the ClientScriptManager object, here is a dummy code I put together so you can look them up and have an idea so you can find out more, this is not meant to be full code.
ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "YourLabelForThis"))
{
script.RegisterClientScriptBlock(this.Page.GetType(), "YourLabelForThis",
"<script type=\"text/javascript\">var MyVariable = "Dummy text";</script>", false);
}
Please note you have to place the js code as an include or further code in the right position in the page whther you want it before or after this code, so lookup RegisterStartupScript or RegisterClientScriptBlock via the ClientScriptManager. To see where your code will be placed and how you should handle it. Also look at the page source in your browser to also see it.
I'm trying to pass a c# variable as an argument to a java-script function like
<%var count=model.SomeMode.Count();%>
when i pass it to my java script function "checkAll(count)" it does not fire but without the argument its workin fine
CheckAll
Remember the page gets created however you wish. So, you could do something like:
<script type="text/javascript">
var count = <%=model.SomeMode.Count(); %>;
</script>
You could apply the same logic in method calls, so you could do:
CheckAll
Javascript can't see your C# source directly - you need to write it into the Javascript source on the server side:
CheckAll
It should look like this:
<script type="text/javascript">
var count=<%=model.SomeMode.Count()%>;
</script>
Currently you're declaring your variable in C#, not outputting it in the page as a JavaScript one. Instead, you want to declare var count literally in the page and have it set to the output of model.SomeMode.Count().
This might be good for your solution:
<a href="#" onclick='return checkAll(<%=count%);'>CheckAll</a>
But there is an other way of doing this instead of conventional way:
Sharing Variables Between JavaScript and C# by Fredrik Kalseth
I'm trying to read the value of a C# property from my code behind file into some JQuery script (see below). The JQuery selector I've written accesses an ASP.Net GridView and then a CheckBox field within the gridview. Whenever a checkbox is checked or un-checked the code is hit, but I need to access the C# property from the code behind to take the appropriate action based on the value of the property.
$(".AspNet-GridView-Normal > td > input").click(function() {
//Need to access the C# property here
//Take action here based on the value of the C# property
});
This may be stating the obvious, but the code behind doesn't exist on the client side where your jQuery code is executing. What you could do is assign the value of the property to a hidden field on the server side so that when you need to check it with jQuery on the client side it will be available. So you might do the following on the client side.
Markup:
<asp:HiddenField ID="hfValueINeedToKnow" runat="server"/>
Code Behind:
hfValueINeedToKnow.Value = <some value>;
jQuery:
$("#<%= hfValueINeedToKnow.ClientID %>").val();
You might need to make some minor changes to support a value for each row of the grid, but hopefully this explains the general idea.
You mentioned in a comment that the value is an int. And I see it's also a public property in your codebehind. This is trivial now - you don't need to escape the value, nor access it in some round-about way, and you get type safety for free:
<script>
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = <%= AvailableInstalls %>;
});
</script>
Well you can't.
You need to render the C# property in some element (perhaps a hidden field) and then look at it that way.
But explain further: What property are you trying to check?
What I've done for this scenario in the past is to print out my code value into the markup and store whatever it is in a javascript variable, thus making a copy of it available to client-side code. This is a silly example, but hopefully it makes sense:
<%
var messsge = "Hello World!"
%>
<html>
<head>
<script type="text/javascript">
function ShowMessage()
{
var msg = '<%= message %>';
if(msg)
alert(msg);
}
</script>
</head>
</html>
There isn't a really clean way to do this. Your best bet would probably be to use the ClientScript.RegisterClientScriptBlock functionality built into ASP.NET. Here's a good primer.
private int myValue;
protected void Page_Load(object sender, EventArgs e) {
ClientScript.RegisterClientScriptBlock(typeof(Page),
"vars", "<script>var myParams = { p1: " + myValue + ", p2: 'My Name' };</script>");
}
This will put the supplied script on your page towards the top of the form. You can change that too. Obviously, it isn't the prettiest; you are essentially string concatenating a different language, but it will work, and for simple variable declaration isn't too rough on the eyes.
ASP Embedded in JavaScript always makes me nervous from the perspective of script injection attacks and the inability to unit-test your JavaScript.
This build upon an ealier answer:
<script type="text/javascript">
$(".AspNet-GridView-Normal > td > input").click(function() {
var AvailableInstalls = $("#MyHidden").val();
});
</script>
You could move it to a hidden variable:
<input type="hidden" id="#MyHidden" value="<%= AvailableInstalls %>" />
However this doesn't get around the problem of injection. So you could you could add a server-side hidden variable and set it from the Page_Load event function in ASP.NET.
(P.s. you also need the attribute type="text/javascript" in your script tag to make it valid HTML).
If you will put your value into an asp:HiddenField with id hfValueINeedToKnow, the simplest way to retrieve this value client side is
var jsvar = $("[id$=hfValueINeedToKnow]").val();
So you can also place this code in a separate .js file.