Troubles to open ajaxToolkit:ModalPopupExtender with JavaScript - javascript

I'm trying to open a ajaxToolkit:ModalPopupExtender with JavaScript but when I run my code and I call the function from the code behind this crash and show this error.
JavaScript runtime error: Unable to get property 'show' of undefined
or null reference
this is my JavaScript:
<script>
function closeChangeArea() {
$find('ModalChangeArea').hide();
}
function showChangeArea() {
$find('ModalChangeArea').show();
}
</script>
and this is my code:
protected void Btn_Click_Ch_Area(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lb.NamingContainer;
Label ToolChange = (Label)gr.FindControl("Lbl_toolg");
Txt_Tool_Reasign.Text = ToolChange.Text;
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showChangeArea();", true);
}
this is my ModalPoupExtender
<ajaxToolkit:ModalPopupExtender
ID="ModalChangeArea"
runat="server"
TargetControlID="hid"
PopupControlID="ChangeArea"
RepositionMode="RepositionOnWindowResizeAndScroll"
DropShadow="true"
PopupDragHandleControlID="moveArea">
</ajaxToolkit:ModalPopupExtender>

In asp.net control id is dynamically appended with container, in that case you will not get the control using $find to get control use clientid of asp.net control or set ClientIdMode = "Static".
Try below code to access element.
$find('<%= ModalChangeArea.ClientID %>').show();
$find('<%= ModalChangeArea.ClientID %>').hide();

Related

Not getting hiddenfield value in javascript

I have an issue in getting the hidden field values, which is been set in page load at code behind. Problem is when i try to get that set values in javascript its giving undefined or null. Not able to get the values which was set in page load at code behind.
//cs code is like this
protected async void Page_Load(object sender, EventArgs e)
{
HiddenField_alt_edit.Value = "[{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]";
ClientScriptManager script = Page.ClientScript;
script.RegisterClientScriptBlock(this.GetType(), "Alert", "<script type=text/javascript>addAlternativeRowWithData();</script>");
}
//aspx page declaration goes like this. Also i am using a master page.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:HiddenField ID="HiddenField_alt_edit" runat="server" Value="i am on."/>
</asp:Content>
// javascript file code goes like this
function addAlternativeRowWithData(mode)
{
alert("test");
var idvalue = $("#HiddenField_alt_edit").val();
alert(idvalue);
alert($nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val());
var myHidden = document.getElementById('<%= HiddenField_alt_edit.ClientID %>').value;
alert(myHidden);
var json_string = $nonconfli('#ContentPlaceHolder1_HiddenField_alt_edit').val();
var arr_from_json = JSON.parse(json_string);
alert("test 2");
alert(arr_from_json);
}
The id generated at client side can differ as the Hidden field is server side control in your code as you have set runat="server".
There are two ways normally. Either make the ClientIDMode static or use the instance in form to get client side id.
Like:
<asp:HiddenField ID="HiddenField_alt_edit" ClientIDMode="static" runat="server"
Value="i am on."/>
and then following should work:
var idvalue = $("#HiddenField_alt_edit.ClientID").val();
or in client side code you need to get id like below:
var idvalue = $("#<%= HiddenField_alt_edit.ClientID %>").val();
Change:
HiddenField_alt_edit.Value = [{"unitid":"3072","unit_nameeng":"BOTTLE","purchcost":"2.000","salrate":"4.000","avgcost":"2.000","factor":"2"},{"unitid":"3073","unit_nameeng":"PKT","purchcost":"10.000","salrate":"20.000","avgcost":"10.000","factor":"10"}]
To this:
HiddenField_alt_edit.Value = "
[{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]"
Then, add this:
<asp:HiddenField ID="HiddenField_alt_edit" runat="server" Value="i am on." ClientIDMode="Static" />
In you js, you have to put this:
const value = document.getElementById('HiddenField_alt_edit').value
const jsonString = JSON.stringify(value)
const json = JSON.parse(jsonString)
console.log(json)
<input hidden id="HiddenField_alt_edit" value="[{'unitid':'3072','unit_nameeng':'BOTTLE','purchcost':'2.000','salrate':'4.000','avgcost':'2.000','factor':'2'},{'unitid':'3073','unit_nameeng':'PKT','purchcost':'10.000','salrate':'20.000','avgcost':'10.000','factor':'10'}]">

Issues with onclick/onserverclick with buttons, HtmlButtons, and LinkButtons

I'm having an issue with the functions to be called not firing off.
I have moved from hardcoding the buttons on HTML, to using the add controls method in the cs; and I have shifted from using Button and HtmlButton to using LinkButton. However none of these seem to work. In Onserverclick and onclick not work Anup Sharma recommends using the LinkButton, and Keyvan Sadralodabai indicates that if the runat="server" is displayed in the insect element, then he control was set up wrong.
So here's a stripped down simplified version of what I'm working with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
public partial class backCodeExper : System.Web.UI.Page
{
protected void saveRecord(string recordID, string buttonId, string dropdownId)
{
PlaceHolder db = Page.FindControl("TestingCS") as PlaceHolder;
HtmlTable tbl = db.FindControl("TestTable") as HtmlTable;
HtmlTableRow tr = tbl.FindControl("TheRow") as HtmlTableRow;
HtmlTableCell tc = tr.FindControl("TheCell2") as HtmlTableCell;
DropDownList ddl = tc.FindControl(dropdownId) as DropDownList;
var status = ddl.SelectedValue.ToString();
HttpContext context = HttpContext.Current;
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=localhost; Database********; User=********; Password=********; Port=3306";
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "updatetesttable";
cmd.Parameters.AddWithValue("#param", status);
cmd.ExecuteNonQuery();
}
protected void Page_Load(object sender, EventArgs e)
{
HtmlTable myTable = new HtmlTable();
myTable.ID = "TestTable";
myTable.BorderColor = "teal";
myTable.BgColor = "black";
TestingCS.Controls.Add(myTable);
HtmlTableRow newRow;
HtmlTableCell cell;
DropDownList DropList;
LinkButton saveButton;
newRow = new HtmlTableRow();
newRow.ID = "TheRow";
cell = new HtmlTableCell();
cell.ID = "TheCell1";
DropList = new DropDownList();
DropList.ID = "StatusDD";
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("A", "1"));
DropList.Items.Add(new ListItem("B", "2"));
DropList.Items.Add(new ListItem("C", "3"));
cell.Controls.Add(DropList);
newRow.Cells.Add(cell);
cell = new HtmlTableCell();
cell.ID = "TheCell2";
cell.BgColor = "black";
saveButton = new LinkButton();
saveButton.ID = "saveButton";
saveButton.CommandName = "saveRecord";
saveButton.CommandArgument = "'1A',this.id,'StatusDD'";
saveButton.BackColor=Color.Green;
saveButton.ForeColor=Color.Cyan;
saveButton.BorderColor=Color.Maroon;
saveButton.Text = "Save";
saveButton.Visible = true;
cell.Controls.Add(saveButton);
newRow.Cells.Add(cell);
myTable.Rows.Add(newRow);
}
}
It loads the screen just fine with the simple dropdown and with the (unstylish) button (frankly the HtmlButton looks much nicer, but I'm aiming for functionality first).
When I select an item from the dropdown and then click save, the screen appears to refresh, keeping the value of the dropdown the same as that which was selected. However, when I check the database, the procedure hasn't fired. Additionally I cannot get this code segment Response.Write("<script>alert('Hello');</script>"); to execute when placed in the method/function saveRecord.
Furthermore, when I run the debugging mode and put break points in saveRecord, none of them are hit.
After inspecting element, this is what I get:
InspectElementResults
Any suggestions? What am I missing?
If I don't use LinkButton (or Button/HtmlButton with onServerClick) then I get errors saying the function isn't defined - which makes since as the function/method is define on the aspx.cs not the aspx within JS script tags.
I've got it figured out. At least, it is functional.
I was trying to set the function to pass the values I want in the format I wanted, but apparently the when you set up a LinkButton, it prefers the object and Event Args as parameters, and the object is the ListButton itself, so if that ListButton object holds the values you need in its attributes, then when the function is called you parse out the attributes you need. There's likely a better way than to assign the two values I need to CommandName and CommandArgument, but this works. (I had thought of using .Attributes.Add("ROW_ID","1a") and .Attributes.Add("DD_ID","StatusDD") ... but couldn't initially figure out how to retrieve those values from the sender object...to be investigated later, in the meantime, rolling forward with a functional solution.
...
protected void saveRecord(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
string ROW_ID = (string)lb.CommandName;
string DD_ID = (string)lb.CommandArgument;
Response.Write("<script>alert('Hello');</script>");
...
}
protected void Page_Load(object sender, EventArgs e)
{
...
saveButton.CommandName = "1a";
saveButton.CommandArgument = "StatusDD";
saveButton.Click += new EventHandler(saveRecord);
...
}
}

Async Javascript callback not triggering the RaiseCallBackEvent function

In my asp.net application I used the async javascript callback.
The requirement is once the user enters the Postal code an async javascript callback function should be called. And the server side code must return me the city with respect to the postal code.
The coding I did is:
<asp:TextBox ID="txtPostCode" runat="server" CssClass="textbox" onchange="javascript: getCityAndStreet();" BorderStyle="Ridge" Height="20px" style="margin-left: 10px" Width="442px"></asp:TextBox>
This textbox onchange it will call the javascript function getCityAndStreet()
function getCityAndStreet()
{
var postalCode = document.getElementById('<%=txtPostCode.ClientID%>');
CallServer(postalCode.value, "");
}
function ReceiveCityAndStreet(rValue,context)
{
alert(rValue);
var city = document.getElementById('<%= txtCity.ClientID%>');
city.value = rValue;
}
Here the CallServer is the server side runtime javascript which is registered as below
protected void Page_Init(object sender, EventArgs e)
{
String cbReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCityAndStreet", "context",true);
String callbackScript;
callbackScript = "function CallServer(arg, context)" + "{ " + "alert('Entered inside CallServer' + arg);" + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
}
I implemented the ICallBackHandler and by this I got 2 methods:
string ICallbackEventHandler.GetCallbackResult()
{
return cityAndStreet;
}
void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
txtStreet.Enabled = true;
txtCity.Enabled = true;
cityAndStreet = eventArgument;
}
in page_load function I just disabled the txtStreet.Enabled. txtCity.Enabled text boxes and on the raise callbackevent I am enabling it.
The issue here is the RaiseCallBackEvent is not working. I mean its not been triggered implicitly.
(This application is not accessed directly in the browser it is accessed through the SharePoint site)
I think the problem is that your button actually does postback when you click on it. You do not need postback because you are calling server using AJAX. Try changing onchage handler to this:
onchange="getCityAndStreet();return false;"
This will cause your button not to trigger postback.
EDIT: Also i want to mention that you cannot change controls in RaiseCallBackEvent method. It is not an actual postback. You need to enable text fields using javascript in onSuccess method.

ASP.NET: HtmlGenericControl <DIV> - refresh

I have a DIV element:
<div runat="server" id="path">Nothing here... yet</div>
and JavaScript which changes its content dynamically. After some actions my element looks like this (tested with Firebug, JS is ok):
<div runat="server" id="path">FirstTest - SecondTest - ThirdTest</div>
Then I'd like to save it to text file (<asp:Button runat="server"...):
<script runat="server">
void Page_Load(Object sender, EventArgs e)
{
Button1.Click += new EventHandler(this.GreetingBtn_Click);
}
void GreetingBtn_Click(Object sender, EventArgs e)
{
HtmlGenericControl path = (HtmlGenericControl)Page.FindControl("path");
Response.AddHeader("content-disposition", "attachment;filename=download.txt");
Response.ContentType = "text/plain";
Response.Write(path.InnerText);
Response.Flush();
Response.Clear();
Response.End();
}
</script>
It also works OK (SaveDialog popups, user choose location), but... in output file there's only one line "Nothing here... yet". It looks like he doesn't react to changes made by JavaScript!
How can I force him to refresh DIV, so I can always save up-to-date content?
Thanks for any help!
You could update an asp:Hidden with the new value and use that value instead on the post back. The PlaceHolder control is not designed to be a two-way control.
E.g.
function UpdateText()
{
var text = ...;
document.getElementById("<%= path.ClientID %>").innerText = text;
document.getElementById("<%= pathHidden.ClientID %>").value = text;
}

Why "this.href" does not get the href value I assigned

I am trying to get the value of the href as i need to pass a variable in query string
<a id="CA" class="CA" href='<%#"mysecondpage.aspx?ID=" + Td1.InnerText %>'
onclick="return popitup(this.href)" runat="server">comment</a>
I have to open a popup in which the "mysecondpage" should be open with a value inside a query string but this.href returns blank value and i dont know why it is not working as it worked inside itemtemplate (gridview) i have used table and filled data with angularJS repeat.
this is my popitup function:
function popitup(url) {
alert(url);
// window.open(url+id,'popup', 'width=700,height=800,scrollbars=no,resizable=no');
return false;
}
You are using a DataBinding expression <%# %>. So you have to call DataBind() in the Page_Load explicitly.
protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}
If you are using Jquery,
Try this I hope it will help you
$(document).ready(function(){
$('#CA').on('click' function(event){
event.preventDefault();
var url = $(this).attr('href');
alert(url);
});
});
Get back to me if is not working

Categories