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.
Related
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.
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;
}
I've written a function (addCalendarEvents) which takes in an array (events) and parses into a custom calendar. Everything works perfectly fine when its fired through the document.ready function, events are registering and etc.
Javascript
$(document).ready(function () {
loadCalendar(null);
addCalendarEvents([{ title: 'All Day Event', start: '2016-01-01' }, { title: 'Long Events', start: '2016-01-07', end: '2016-01-10' }]);
});
function addCalendarEvents(events) {
$('#calendar').fullCalendar('addEventSource', events)
}
However, I also need them to be fired through the code behind to add events dynamically. I've tried using ScriptManager's RegisterStartupScript, but it's not working. Is there a proper way for me to do so?
C# Code Behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "addEvents", "addCalendarEvents([{ title: 'Other Event', start: '2016-01-01' }, { title: 'Other Long Events', start: '2016-01-07', end: '2016-01-10' }]);", true);
}
It might be simpler to use a <asp:Literal id="StartupScript" runat=server /> control containing the $(document).ready() function to inject your page load callouts.
You could write the statements to the literal control within your Page_Load event and they should get executed by the client when the page is ready.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<asp:Literal ID="CodeInject" runat="server"/>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
And the code behind is:
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder SB = new StringBuilder();
SB.Append("<script>");
SB.Append("$(document).ready(function () {");
// statements here
SB.Append("alert('test');");
SB.Append("});</script>");
CodeInject.Text = SB.ToString();
}
try to convert the data into json while adding the script. Add your assemblies
using this Assembly
using System.Web.Script.Serialization;
Then Deserialize your object
var json = new JavaScriptSerializer().Serialize(obj);
then call registerStartupScript
ScriptManager.RegisterStartupScript(this, this.GetType(), "addEvents", json, true);
and at client side do this to convert it into json
var obj = JSON.parse(string);
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);
}
}
on view page I have and inside javascript code I want to access to my Model.Id. How this can be done?
#model MyModel
<script type="text/javascript">
function initialize() {
var id = model.Id // this doesnt work
}
</script>
Thanks
You need to keep track of what's on the server and what's on the client. The #Model variable is only used on the server, Javascript has no notion of the model object, so you need to print the values out in the html.
<script type="text/javascript">
function initialize() {
var id = "#Model.Id"; // this will work
}
</script>
Make model.id to "#Model.id" Like :
#model MyModel
<script type="text/javascript">
function initialize() {
var id = "#Model.Id"
}
</script>
This should work. Still need to use the razor syntax..#.
#model MyModel
<script type="text/javascript">
function initialize() {
var id = "#Model.Id" // this doesnt work
}
</script>