JavaScript function not defined in c# code - javascript

I am working with VS, a web form application, and I want to generate in the code-behind (C#) a JavaScript function defined in a JavaScript file in the project,.
I have tried different ways ,such as this line of code:
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Function_Name", true);
However, it can't resolve the name of my function since it's "not defined" as it's shown as a JavaScript error. But it works fine with a simple line of JavaScript code put in the Function_Name field (like alert("something")).
Any help with this please?

C#
define your javascript inside the C# code as text
Type type = this.GetType();
String key = "CallMyFunction";
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsClientScriptBlockRegistered(type, key))
{
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
script.AppendLine(" function Function_Name() {");
script.AppendLine(" frmMain.Message.value = 'Hello World';");
script.AppendLine(" }");
script.AppendLine("</script>");
cs.RegisterClientScriptBlock(type, key, script.ToString(), false);
}
or read your javascript from a .js file
<script type="text/javascript">
function Function_Name() {
frmMain.Message.value = 'Hello World';
}
</script>
Type type = this.GetType();
String key = "CallMyFunction";
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsClientScriptBlockRegistered(type, key) && File.Exists(path))
{
string script = File.ReadAllText(path);
cs.RegisterClientScriptBlock(type, key, script, false);
}
HTML - Body
<body>
<form id="frmMain" runat="server">
<input type="text" id="Message" />
<input type="button" value="Click!" onclick="Function_Name()" />
</form>
</body>
If you need a one-liner:
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "function Function_Name() { frmMain.Message.value='Hello World'; }", true);
or
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "<script type=\"text/javascript\">function Function_Name() { frmMain.Message.value='Hello World'; }</script>", false);
EDIT:
Using includes
String includeKey = "MyInclude";
String includeFile = "/myInclude.js";
String scriptKey = "CallMyFunction";
String script = "Function_Name();"; //Function inside your included js file.
Type type = GetType();
ClientScriptManager cs = Page.ClientScript;
//register the js file containing the function
if (!cs.IsClientScriptIncludeRegistered(includeKey))
{
cs.RegisterClientScriptInclude(includeKey, includeFile);
}
//register the script to call the function
if (!cs.IsClientScriptBlockRegistered(scriptKey))
{
cs.RegisterClientScriptBlock(type, scriptKey, script, true);
}

Related

How to pass values to an external Javascript script from ASP.NET

I have a set of KPI data I need to pass over to a Javascript file from my ASP.NET project. I thought I could do so using a ViewBag... Here is what is in the controller:
public ActionResult KPI()
{
if (Session["OrganizationID"] == null)
{
return RedirectToAction("Unauthorized", "Home");
}
else
{
int orgId;
int.TryParse(Session["OrganizationID"].ToString(), out orgId);
var user = db.Users.Find(User.Identity.GetUserId());
var organization = user.Organizations.Where(o => o.OrganizationID == orgId).FirstOrDefault();
var reports = db.Reports.ToList();
try
{
var org_reports = (from r in reports
where r.OrganizationID == organization.OrganizationID
select r).ToList();
var kpi = new KPI(org_reports);
var jsonKPI = JsonConvert.SerializeObject(kpi);
ViewBag.orgData = jsonKPI;
}
catch (ArgumentNullException e)
{
return RedirectToAction("Unauthorized", "Home");
}
}
return View();
}
From the View I've tried using hidden values, and also just passing them in as parameters when calling the script:
<input type="hidden" id="orgData" value=#ViewBag.orgData>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
I then want to read this value in my JS script and parse it into JSON from the string:
function myFunction(){
var test1 = JSON.parse(document.getElementById('orgData'); // Doesn't work
var test2 = JSON.parse(orgData); // Doesn't work
}
It doesn't appear that any of these methods are working. What is my mistake here?
You should use Html.Raw, to avoid ASP.NET to escape your value:
orgData = #Html.Raw(ViewBag.orgData);
Also, if this is a Json, it is also a valid JS object, so you don't need to parse, it already is a JS Object.
It looks like you forgot the quotes.
<input type="hidden" id="orgData" value=#ViewBag.orgData>
should be
<input type="hidden" id="orgData" value="#ViewBag.orgData">
Also the code inside your script tag will never get executed because the script tag has a src attribute on it. Code inside script tags with src attributes never gets executed.
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
should be changed to
<script type="text/javascript" src="~/Scripts/KPIs.js" />
<script>
orgData = #ViewBag.orgData;
</script>
I solved it! Pass the KPI model through the view and then it's as easy as:
var orgData = #Html.Raw(Json.Encode(Model));
Thanks to all to offered help.

Invoking a C# Function that doesn't return anything from JavaScript

Consider the following codes:
In my .ascx
<a id="1" onclick="registerLastViewed(this.id);">Example</a>
<asp:HiddenField id="hdID" runat="server" />
<script type="text/javascript>
function registerLastViewed(ID) {
document.getElementById('<%= hdID.ClientID %>').value = ID;
"<%= RegisterLastViewed() %>"; //dies here
}
</script>
In my .ascx.cs
public void RegisterLastViewed()
{
//todo required logic
}
Basically what I plan to do is:
Clicking on <a> will call the Javascript function which will invoke my C# function from code behind.
But everytime I try to get into this page, it dies. Redirect loops and dies.
Is there a way to do this without using webmethod?
for reference, this runs fine:
<script type="text/javascript">
var usr = "<%=getUserId() %>";
</script>
public string getUserId() {
string userId = "";
if (Session[PropertiesKey.SessionKeys.UserObjLoginUser] != null)
{
UserMaster loginUser = (UserMaster)Session[PropertiesKey.SessionKeys.UserObjLoginUser];
userId = loginUser.UserID;
}
return userId;
}

Get value from html input text type textbox as string and pass it to C# hashtable being used in aspx

The textbox is defined as html input text type and takes input from the users. This value is needed to pass as key to hashtable defined in aspx.cs file being used in aspx file. But the correct value is not being given and an exception is being thrown. Any help in this regard would be helpful. Thanks
The code is as follows:
<% =Hashtable[document.getElementbyId("Textbox").Value]%>
document.getElementbyId("Textbox").Value is not giving the correct output. If it is replaced by a string value acting as key then it works fine. The only problem is getting the string value from textbox.
First include jquery in head section
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
Try below code to read textbox value :
First read text box value using
var key = $("[id$=Textbox]").val();
and see if value is present in texbox if present use this to read hash value
<% =Hashtable[key]%>
Try this it worked for me :
aspx :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function GetHashtable() {
alert("<% = hashtable[this.test] %>");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtKey" OnTextChanged="txtKey_TextChanged" AutoPostBack="true" runat="server"></asp:TextBox>
</div>
</form>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
</body>
</html>
Code behind :
public partial class _Default : System.Web.UI.Page
{
protected int test;
public Hashtable hashtable = new Hashtable();
static Hashtable sHashtable = new Hashtable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sHashtable[1] = "One";
sHashtable[2] = "Two";
sHashtable[13] = "Thirteen";
}
}
protected void txtKey_TextChanged(object sender, EventArgs e)
{
test = Convert.ToInt32("0" + txtKey.Text);
hashtable = sHashtable;
Page.ClientScript.RegisterStartupScript(this.GetType(), "GetHashtable", "GetHashtable();", true);
}
}

Value from Grails controller breaking javascript in gsp

I am passing XML string from grails controller to gsp and need to use it in the javascript function for showing treeview using jstree.
My controller code is
render(view: "list",model: [dataXML: callXML.getXmlString()])
The javascript function in gsp code is
function callXML(){
var xmlStr = "${dataXML}";
_uimTree = new UIMTreeProcessor(parseXml(), jQuery("#jstree"));
_uimTree.doProcess();
}
function parseXML(){
if (window.DOMParser) {
return new window.DOMParser().parseFromString(xmlStr, "text/xml");
}else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
}else{
return jQuery(xmlStr);
}
}
Controller:
def showModel = {
CallXML callXML = new CallXML();
callXML.setXmlString();
def productFlowModels = new XmlParser().parseText(callXML.getXmlString());
println callXML.getXmlString();
render(view: "list",model: [dataXML: callXML.getXmlString() as String])
}
As soon as the ${dataXML} comes in function it breaks the code. I tried without quotes, still same problem.
What is that I am doing wrong?
Thanks in advance.
If you have xml string, you should be able to access it from your controller like this:
Controller:
def list(Integer max) {
def xmlString = """<langs type="current">
<language>Java</language>
<language>Groovy</language>
<language>JavaScript</language>
</langs>"""
def xml = new XmlParser().parseText( xmlString )
render (view:'list',model: [dataXML:xml ])
}
GSP:
<!DOCTYPE html>
<html>
<head>
<script>
function my(){
var str = "${dataXML.encodeAsHTML()}"
alert (str)
}
</script>
</head>
<body>
<p>
${dataXML.encodeAsHTML()}
</p>
<script>
my()
</script>
</body>
</html>
in your model, use
render(view: "list",model: [dataXML: JsonOutput.toJson(callXML.getXmlString())])
You need to properly encode strings as javascript strings if you are going to output them in a javascript context.

injection json data in the master page

I'd like to inject some javascript on every page; basically, it's a json string.
In my master page, I have this:
public partial class TheMasterPage : System.Web.UI.MasterPage
{
protected void Page_Init(object sender, EventArgs e)
{
if (Session["TheData"] == null)
{Session["TheData"] = GetData(DateTime.Today.Date;); }
}
}
This checks to see if the session contains the data I need for the json serialization.
What I'd like to do is have the data in the session to be included in the javascript of every page.
In the aspx of the page, I have:
<asp:ContentPlaceHolder id="head" runat="server">
<script type="text/javascript">
var TheJsonData =... ;
</script>
</asp:ContentPlaceHolder>
How do I inject the json data in there? If I do this, which gets executed first? The aspx injection or the Page_Init function?
I use the following code for the serialization:
TheDataList = (List<MyModel>)Session["TheData"];
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new MyModel() });
String result = serializer.Serialize(TheDatatList);
What I want to be able to do is $(document).ready(function () {ShowData(TheJsonData) }); with the variable TheJsonData already loaded when the document ready event fires.
Thanks.
Try like this:
<script type="text/javascript">
var TheJsonData = <%= new JavaScriptSerializer().Serialize(Session["TheData"]) %>;
</script>
And the end result should look something like this:
<script type="text/javascript">
var TheJsonData = [{ prop1: 'value1', prop2: 'value2' }, { prop1: 'value3', prop2: 'value4' }];
</script>
Page_Init will run before the code in the view and would set the value in the session.

Categories