Parse 2D array from ASP.NET C# code behind to Javascript - javascript

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);

Related

How can i do database CRUD operations by taking parameters from aspx.cs file?

<script type="text/javascript">
function GetValue3(id) {
text1 = documnet.getElementById(input parameter from cs file);
alert("this is from cs file");
//database transactions here <-------method1
}
$(function () {
button1 = document.getElementById(input parameter from aspx file);
$("[id*=Button1]").on("click", function () {
alert("this is from aspx file");
//database transactions here <-------method2
})
})
</script>
My question is that there are two procedures for database transactions, first from taking parameters from aspx.cs code befind file and second from aspx file.
In my code i want to do database transactions using second approach (by using parameters from aspx.cs code behind) because it is required in my coding.
please guide me how can i build this approach.
not sure what you are trying to achieve but you need to differentiate between client events and server events
to get element in JS you can get its ID from 'ClientID'
ASPX file:
<asp:TextBox ID="txtTest" OnTextChanged="txtTest_TextChanged" runat="server" AutoPostBack="true" ></asp:TextBox>
<asp:Button ID="btn1" OnClick="btn1_Click" runat="server" Text="Click" />
<script type="text/javascript">
function textFromTextBox() {
var text1 = documnet.getElementById('<%= this.txtTest.ClientID %>');
}
</script>
aspx cs file
protected void btn1_Click(object sender, EventArgs e)
{
var text = txtTest.Text;
}
protected void txtTest_TextChanged(object sender, EventArgs e)
{
var updatedText = txtTest.Text;
}
EDIT:
you cannot attach code behind method to ordinary html element. You can only attach javascript events to these elements or inputs. If its the case then its irrelevant if you are using asp.net web forms, python, ruby on backend server.
<input type="button" id="sbutton" value="Save" />
<script type="text/javascript">
(function (){
documnet.getElementById('sbutton').addEventListener("click", function(){ //do your crud operation });;
})
()
</script>

ASP.Net Webform: Add HTML and javascript dynamically

I need a ASP.net application which is only kind of "pageDisplayer" from content which is coming from an API. So I choose ASP.net Webform and tried the following:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PMLetterAcceptance.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:Literal runat="server" id="JavaScript"></asp:Literal>
</head>
<body>
<form id="letterform" runat="server">
<div>
<%= pageContent %>
</div>
</form>
</body>
public partial class WebForm1 : System.Web.UI.Page
{
protected string pageContent = "";
protected void Page_Load(object sender, EventArgs e)
{
...// here I fetch the html and javascript content from the API
dynamic json = Json.Decode(streamReader.ReadToEnd());
if (json.status != "OK")
pageContent = json.error;
else
pageContent = json.html;
JavaScript.Text = json.script;
}
}
The html content and the script are loaded correct but I cannot access DOM elements in the javascript. The javascript looks like that
(function()
{
function processForm(e)
{
... // Here I want to do some stuff before sending the form
}
let form = document.getElementById('letterform');
if (form.attachEvent)
form.attachEvent("submit", processForm);
else
form.addEventListener("submit", processForm);
})();
No I get the error "form is null". For me it looks like the javascript is executed before the DOM is ready. But how can I change this to make it work like expected?
Try putting the JS (literal) at the bottom of the page, before the closing body tag. That way, the HTML will be loaded before the JS tries to find elements.

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);
}
}

ScriptManager.RegisterStartupScript() method not working - ASP.NET, C#

I have used ScriptManager.RegisterStartupScript() method in order to show an alert when particular thing happens in back end.It works fine in page load method but not in particular method which is called when a specific button is clicked . I Couldn't find a solution because in another page it works fine in both page load and the method.
Script Manager RegisterStartupScript Method
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
HTML
<asp:HiddenField runat="server" ClientIDMode="Static" ID="PostBackController"/>
<button class="some-class" id="btnSave" runat="server" onclick="btnSave_clientClick();">SAVE</button>
Javascript
function btnSave_clientClick() {
// code
if (some_condition) {
$('#PostBackController').val("btn_save");
__doPostBack();
}
}
Page Load Method
protected void Page_Load(object sender, EventArgs e)
{
if (PostBackController.Value == "btn_save")
{
uploadDocSave_ServerClick();
}
}
Method Wish should be called when button Clicked
protected void uploadDocSave_ServerClick()
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
}
My deepest condolences for OP if you still have to work with Webforms. This is how you can solve it in a minimal way while reducing traffic:
Codebehind sample:
public partial class About : Page, IPostBackEventHandler
{
protected void Page_Init(object sender, EventArgs e)
{
// Unless the button is serverside clicking it will reload the page
// registering the page like this prevents a page reload.
var scriptManager = ScriptManager.GetCurrent(Page);
scriptManager?.RegisterAsyncPostBackControl(Page);
}
/// <inheritdoc />
public void RaisePostBackEvent(string eventArgument)
{
var javascriptCode = $"alert('server method called and triggered client again. {DateTime.Now.ToString("s")}');";
// if your key isn't changed this script will only execute once
ScriptManager.RegisterStartupScript(udpMain, typeof(UpdatePanel), Guid.NewGuid().ToString(), javascriptCode, true);
// updating the updatepanel will inject your script without reloading anything else
udpMain.Update();
}
}
Webforms sample:
<script type="text/javascript">
function clientFunction(sender, args) {
alert('client function called');
<%= Page.ClientScript.GetPostBackEventReference(Page, "callServerFunction") %>
args.preventDefault();
}
</script>
<asp:UpdatePanel runat="server" ChildrenAsTriggers="False" UpdateMode="Conditional" ID="udpMain">
<ContentTemplate>
<h2><%: Title %>.</h2>
<h3>Your application description page.</h3>
<p>Use this area to provide additional information.</p>
<button onclick="clientFunction(); return false;">raise server function</button>
</ContentTemplate>
</asp:UpdatePanel>
Try this:
If you Used Update Panels Then You can Use:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);
Other Wise You can Use
ClientScript.RegisterStartupScript
(GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);
Try this:
Client side:
Use Literal Control
<asp:Literal ID="IMsg" runat="server" Text=""/>
Server side:
string msg = "<script>alert('Change successfully');</script>";
IMsg.Text = msg;
I think it will help you. It works fine in my projects.
Try to remove line containing:
__doPostBack();
in the JavaScript code.
Sorry I am late at the party. Use this overload of RegisterStartupScript method, and set the first parameter the button on which you want to click to register the javascript function. Like:
ScriptManager.RegisterStartupScript(btnSave, this.GetType(), "alert", "alert('msg');", true);
Cheers!
THE REALLY SIMPLE WAY
You can wire up a <button runat="server"></button> to a server event using the onserverclick attribute:
HTML:
<button class="some-class" id="btnSave" onserverclick="uploadDocSave_ServerClick" runat="server">SAVE</button>
C# Handler:
protected void uploadDocSave_ServerClick(Object sender, EventArgs args)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
}
WITH CLIENT SIDE VALIDATION
If you want to add some sort of JavaScript check before postback, you can do that from the onclick attribute:
HTML:
<button class="some-class" id="btnSave" onclick="return btnSave_clientClick();" onserverclick="uploadDocSave_ServerClick" runat="server">SAVE</button>
JavaScript:
function btnSave_clientClick() {
// code
if (some_condition) {
return true; // allows the control to do a postback
}
}
C# Handler:
protected void uploadDocSave_ServerClick(Object sender, EventArgs args)
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "alert", "alert('msg');", true);
}

Force asp.net page postback from server

I have a page that is created entirely dynamically in the code behind (oh joy).
On pressing a button on this page, more elements are added to the page - which is fine, however, the refreshed page doesn't appear until the next postback. I would do a redirect, but I want to keep the state of any data entered in the existing controls.
So - I need to force a postback from the server code behind code. I imagine that this involves inserting some js code - but beyond that, I've not had any joy at all.
Here is an example to make things clearer:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
A very simple page.
The code behind is simple too:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["data"] = 1;
}
PopulatePage();
}
private void PopulatePage()
{
int data = (int)Session["data"];
for (int n = 0; n < data; ++n)
{
TextBox tb = new TextBox();
tb.ID = n.ToString();
PlaceHolder1.Controls.Add(tb);
Literal lit = new Literal();
lit.Text = "<br/>";
PlaceHolder1.Controls.Add(lit);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int data = (int)Session["data"];
Session["data"] = ++data;
}
}
You click the button and more controls are added. This is way simpler than the page that I am having issues with, but it demonstrates the problems that I am having.
The postback is not needed and is a bit of a hack, you would be better off fixing the problem at the root.
private void PopulatePage()
{
for (int n = 0; n < Counter; n++)
{
CreateSingleControl(n);
}
}
private void CreateSingleControl(int index)
{
TextBox tb = new TextBox();
tb.ID = String.Format("text{0}", index);
PlaceHolder1.Controls.Add(tb);
Literal lit = new Literal();
lit.Text = "<br/>";
PlaceHolder1.Controls.Add(lit);
}
protected override void CreateChildControls()
{
PopulatePage();
base.CreateChildControls();
}
protected void Button1_Click(object sender, EventArgs e) {
CreateSingleControl(Counter);
Counter++;
}
private int Counter
{
get
{
return Counter = (int)(ViewState["data"] ?? 1);
}
set
{
ViewState["data"] = value;
}
}
Use the Request forms list to search unique control ID's
Something like this link below, last post, not sure his code is exactly correct, but you'll get the idea.
Searching for controls in Request.Form / Parsing a NameValueCollection
Give your controls unique IDs' and you can search for them on the postback.
Plus, i use to add other things to the ID to let the postback searching know what type of control it was, like adding txt_firstname, i know that firstname was a txtbox. Use regex to search the returned strings.

Categories