pass a c# variable to javascript function - c#

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

Related

pass parameter to one function in the code behind in C# from javascript

I am trying to pass parameter to one function in the code behind in C# from javascript
<script type="text/javascript">
$(document).ready(function () {
$("#some_id").click(function () {
var id = document.getElementById('HiddenField2');
var a = <%=btn_Click(id)%>;
});
});
</script>
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "item_id")%>' />
code behind
public string btn_Click(String item_id)
{
/*do some thing*/
return null;
}
But this piece of code always giving me error of context. That id is not defined in this context.
Can some please let me know what wrong i am doing?
First, var id is javascript and the code within <%= %> is C#. You can't pass a variable between the languages like that.
Second, the value of id in this case is going to be a DOM element which C# can't use anyways. If you want to get the value of HiddenField2 within the code behind you can use HiddenField2.Value.
Third, since you're using ASP.net, instead of using jQuery's .click handler you should use the onServerClick attribute to wire up the button click behavior to btn_Click.
The button click event in C# will be triggered by Postback when your browser post data back to asp.net
I do not understand why you use HiddenField here,so my suggestion do not consider about it
Solution 1:
first you can extract your code in btn_Click to a HttpHandler(*.ashx in asp.net),then use Ajax by using js framework like jQuery to send data to your HttpHandler,data returned by HttpHandler can be processed by js
sample code is here
Solution 2:
if your code in btn_Click is relevent to your page, just use ajax Get method, the data will send to your page,the data returned by your data will be processed by js too
In the end, if you are new to web, I recommend you to learn or implement asp.net MVC, in my opinion, it is more flexible than asp.net webform

HTML Helper in JavaScript?

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.

How to pass data from SQL Server to jQuery var [Flot]

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.

Calling ASP method inside javascript code

i wonder if there is any way to call an asp method that returns a string or something when you are in <script></script> tags.
Like this (it does not work):
<script language="javascript" type="text/javascript">
function isValid() {
var required = "<%= callAspMethodThatReturnsSomething() %>";
}
</script>
any help with this? thx!
There is no direct way to call c# method like in example above. But you can send $.ajax request to the server, or even send postback using _doPostBack(..,..)
The issue is that you are calling a method on the master page from the content page directly.
You can't do that - you need a reference to the strongly typed master page.
Try this (asp.net 4.0):
<%:((MasterPageClassName)Page.Master).callAspMethodThatReturnsSomething()%>
Or this (pre 4.0):
<%=((MasterPageClassName)Page.Master).callAspMethodThatReturnsSomething()%>
<% callAspMethodThatReturnsSomething() %>
this method in <% %> will work before what you want to do ,it may looks like does not work
yet,you can create a new button on page ,make it unvisible and use it's click event like document.getElementById("<%=button1.ClientID%>").click()

Reading C# property into JQuery code

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.

Categories

Resources