I am trying to toggle showing/hiding a html element from within a C# function.
Things I've tried based on previously answered questions:
calling the html element's id via the code behind
Calling a J-query function from the code behind using Page.ClientScript.RegisterStartupScript.
Same as above but using: ScriptManager.RegisterStartupScript(this.GetType(), this.GetType(), "script", "HideMonthSelector();", true);
C# function:
Namespace NamespaceName.Geotext
{
public class ClassName
{
private void FunctionName(int objectUid, int ddsUid, string month, string year, bool toggle)
{
Default CodeBehind = new Default();
CodeBehind.HideMonthSelector();
}
}
}
Code Behind
Namespace NamespaceName
{
public partial class Default : System.Web.UI.Page
{
public string VersionNumber = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
HtmlHead head = Page.Header;
foreach (Control child in head.Controls)
{
if (child is HtmlLink)
{
((HtmlLink)child).Href += "?" + VersionNumber;
}
}
}
public void HideMonthSelector()
{
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "HideMonthSelector();", true);
}
}
}
Default.aspx:
<li runat="server" id="selectMonth" class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">
<i class="fa fa-calendar" aria-hidden="true"></i> Select Month
</a>
<ul class="dropdown-menu" id ="navDropCalendar"></ul>
</li>
<script>function HideMonthSelector() { $("#selectMonth").hide();}</script>
<script>function ShowMonthSelector() { $("#selectMonth").show();}</script>
EDIT: based on the comments, it appears that the issue is that I am creating an instance of the default.aspx.cs page and then calling a method in that instance. Apparently this means that the html id element is not initialised and remains null. What other alternative is there?
I am able to run Default.HideMonthSelector() if I change the HideMonthSelector function to a static field, but then the code within that function errors (object reference required for the non-static field)
The problem lies in your javascript code
<script>function HideMonthSelector() { $("#monthSelector").hide();}</script>
<script>function ShowMonthSelector() { $("#monthSelector").show();}</script>
I can't find the any html element with id monthSelector. That's why your code isn't working.
Related
i'm using the same js script call in both scenarios... one it is called from a button_click event and it works properly (changes the label text) as per below...
public void Test_OnClientClick(object sender, EventArgs e)
{
Console.WriteLine("test");
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
When it is called from an event raised by a redis subscription, the same call does not work...
public void Page_Load(object sender, EventArgs e)
{
// Establish connection
redisConn = ConnectionMultiplexer.Connect(redisIP);
rbsub = redisConn.GetSubscriber();
rbsub.Subscribe(ServerRedisChannel).OnMessage(channelMessage => {
MessageHandler(channelMessage.Message.ToString());
});
}
public void MessageHandler(string cm)
{
try
{
//Test_OnClientClick(null, null);
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
catch (Exception e)
{
var x = e;
}
}
I confirm it reaches the ClientScript call in MessageHandler with a breakpoint but it never reaches the debugger in the js script.
Full code below:
Default.aspx
<%# Page Title="Home Page" Async="true" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForm._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function updateText(strData) {
debugger;
document.getElementById("<%=lblTest.ClientID%>").innerHTML = strData;
}
</script>
<div class="jumbotron">
<h1>redis test</h1>
<p><asp:Label ID="lblTest" runat="server" Text="redis output"></asp:Label></p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Test_OnClientClick"/>
<p>Learn more ยป</p>
</div>
</asp:Content>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StackExchange.Redis;
namespace WebForm
{
public partial class _Default : Page
{
ConnectionMultiplexer redisConn;
ISubscriber rbsub;
public const string redisIP = "gptdevnj01:6379";
public const string ServerRedisChannel = "ac";
public const int redisDB = 7;
public void Page_Load(object sender, EventArgs e)
{
// Establish connection
redisConn = ConnectionMultiplexer.Connect(redisIP);
rbsub = redisConn.GetSubscriber();
rbsub.Subscribe(ServerRedisChannel).OnMessage(channelMessage => {
MessageHandler(channelMessage.Message.ToString());
});
}
public void MessageHandler(string cm)
{
try
{
//Test_OnClientClick(null, null);
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
catch (Exception e)
{
var x = e;
}
}
public void Test_OnClientClick(object sender, EventArgs e)
{
Console.WriteLine("test");
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
}
}
So i suppose the question boils down to calling a js script from a button_click event differs from when it is called from a subscription (or async) event?
Response to a button click happens within ASP.NET Page Lifecycle, whereas handling of an asynchronous message from a Redis subscription will most likely:
happen completely outside of that lifecycle, and
in a completely different thread.
Unless you synchronize those threads somehow (one that handles the request and one that handles received messages) - your call to ClientScript.RegisterStartupScript will go to void, to wrong client or simply fail. Please note however that the nature of asynchronous operations may require a different approach from your side rather blocking a thread to wait for a message.
I want to pass a HTML element value to an Android application. I
I tried retrieving the value using the code below:
document.getElementById(\"summary\").value --> giving null value
document.getElementById(\"summary\").innerHtml --> giving null value
document.getElementById(\"summary\").textContent --> giving null value
I'm trying to implement javascript MutationObserver. So whenever there is a change in the content, I can immediately pass the value to the android java code.
Can anyone help me?
I used the following code:
myWebView = (WebView)this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("https://helloworld.com/details");
myWebView.addJavascriptInterface(new JavaScriptInterface(this, myWebView), "MyHandler");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
myWebView.setWebContentsDebuggingEnabled(true);
}
myWebView.evaluateJavascript("(function(){return document.getElementById(\"summary\").textContent})();",
new ValueCallback<String>() {
#Override
public void onReceiveValue(String html) {
Log.e("HTML Content",html);
}
});
This is my HTML code:
<div class="well" id="summary" *ngIf="viewModel != null">
<div class="SuccessSummary">{{viewModel.successSummary}}</div>
</div>
Try this
myWebView.evaluateJavascript("(function(){return
document.getElementById('summary').innerHTML})();",
new ValueCallback<String>() {
#Override
public void onReceiveValue(String html) {
Log.e("HTML Content",html);
}
});
I need call codebehind function with parameter which is instance of some Entity class from script tags in aspx page. Im created popup windows from kendo ui using kendotemplate and in this template i need my form with inputs and button used in code behind. Something like this http://demos.telerik.com/kendo-ui/grid/custom-command but when i add asp items to template tags not work for me.
My entity:
public class Person
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
public int Age { get; set; }
}
code behind function:
protected void btnAddPerson_Click(object sender, EventArgs e)
{
Person p= new Person();
// get values from three inputs
p.FirstName= personFirstName.Value;
p.LastName= personLastName.Value;
p.Age = Convert.ToInt32(personAge.Value);
...
}
i need in javascript something like this:
<script type="text/x-kendo-template" id="template">
<Asp:Input ...>
<Asp:Input ...>
<Asp:Input ...>
<Asp:Button ...>
</script>
and sorry for my english
i'm developing a .net application using twitter bootstrap.
I'm trying to get data from .aspx.cs page to .aspx page.
Please find my code below:
strOblect.cs
public class strObject
{
public string Name { get; set; }
public string Description { get; set; }
}
.aspx.cs page:
public List<strObject> stringList = new List<strObject>();
protected void Page_Load(object sender, EventArgs e)
{
strObject ObjOne=new strObject();
ObjOne.Name="One";
ObjOne.Description ="One";
stringList.Add(ObjOne);
strObject ObjTwo=new strObject();
ObjTwo.Name="Two";
ObjTwo.Description ="Two";
stringList.Add(ObjTwo);
strObject ObjThree=new strObject();
ObjThree.Name="Three";
ObjThree.Description ="Three";
stringList.Add(ObjThree);
}
.aspx:
<asp:Panel ID="pnlData" runat="server" style="background-color:White;">
<script type="text/javascript">
$(document).ready(function () {
var valueAssigned=stringList;
});
</script>
</asp:Panel>
I'm unable to get stringList value in $(document).ready.
Please help me out to get the value.
It appears that your stringList is actually a collection of objects. In order to use it in JavaScript as such, you'll need to serialize it to a javascript object.
var valueAssigned=<%=new JavaScriptSerializer().Serialize(stringList)%>;
So that you can wind up with the following:
var valueAssigned= [{Name: "Foo", Description: "Bar"}, {...}];
Edit
JavaScriptSerializer is in System.Web.Script.Serialization - you'll either need to add this below at the top of your <%# Page
<%# Import Namespace="System.Web.Script.Serialization" %>
or specify the FQ name
var valueAssigned=<%=new System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(stringList)%>;
StuartLC's answer will be enough.JSON is very good option for that purpose. Other option can be to register client script in aspx.cs. Here is another SO question regarding that
How do I pass data from c# to jquery/javascript?
I set some hidden filed value in document.ready function In which event of page life cycle I cant access the value of that hidden filed here is Code
$("document").ready(function () {
StatdIds = $("input[id$=hdnSelectedStateIDs]").val();
$("input[id$=hdnSupplierID]").val($("input[id$=hdnSupplierID]").val());
$("input[id$=hdnShippinRateID]").val($("input[id$=hdnShippingId]").val());
$("body").click(function (e) {
if (e.target.id != 'dvNewPostSettings-ddlFilter') {
$("#dvNewPostSettings-dvSearchFilterActions").hide();
}
});
});
and Page Code is
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim supplierID As Integer = hdnSupplierID.Value
Dim ShippingRateID As Integer = hdnShippinRateID.Value
End Sub
You might have used something like below:
<div id="div<%= Test %>">
</div>
Declare one property in your page like:
public string Test { get; set; }
and assign value in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Test = "Hello World";
}
}
Run the page and you can see in rendered page the id of the div is changed to "divHello World".
So you can not access the value of hidden field that you set in document.ready as it fires once all the page life cycle events are fired.