having issue with updating label asynchronously - javascript

I am trying a simple ajax form where it will update a label on button click.
I get the below error:
Microsoft JScript runtime error:
Sys.WebForms.PageRequestManagerParserErrorException: The message
received from the server could not be parsed.
at below function on line : "throw error;"
function Sys$WebForms$PageRequestManager$_endPostBack(error, executor, data) {
if (this._request === executor.get_webRequest()) {
this._processingRequest = false;
this._additionalInput = null;
this._request = null;
}
var handler = this._get_eventHandlerList().getHandler("endRequest");
var errorHandled = false;
if (handler) {
var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, data ? data.dataItems : {}, executor);
handler(this, eventArgs);
errorHandled = eventArgs.get_errorHandled();
}
if (error && !errorHandled) {
***throw error;***
}
}
Here is my form code:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<script runat="server">
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Hello";
}
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Test Form
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" runat="server">
<div style="text-align: left; height: 395px;">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" style="margin-left: 66px" Text="Button" Width="176px" />
<br />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</asp:Content>
Am I missing something?

I inserted the code above into empty aspx page, removed reference to masterpage and asp:Content and it worked for me. The label changed its text.
If it still doesn't work for you you may use Firefox+Firebug to see the actual server response after clicking on a button. It may contain detailed exception that will give you a hint.

Related

ASP.Net WebForms not firing UI events from codebehind file

I have simple UI in aspx file, with aspx.cs codebehind. No matter what kind of control I use, events from this file wont fire - the only ones that are working are events like Init, PageLoad.
Events are created via designer.
What I tried:
Basic OnClick on markup page
OnClick in designer
Inline c# Code in markup page via javascript
PageMethods
Pure javascript click
Whole new page
When I add for example alert for click event in javascript, it works. But Im not able to run my c# code after user clicks on button.
I have also removed everything from file (validation, other controls...), but not even then my code works.
There are also no errors in console
Markup Page
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/Views/Shared/Site.Master" EnableEventValidation="false" CodeBehind="Report.aspx.cs" Async="true" Inherits="App.Web.Views.Besparingen.Report" %>
<%# Register Assembly="Microsoft.ReportViewer.WebForms" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:Content runat="server" ContentPlaceHolderID="Content" ID="Content1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('[id*=selectYear]').multiselect({
includeSelectAllOption: true
});
});
</script>
<script type="text/javascript">
$(function () {
$('[id*=selectPortfolio]').multiselect({
includeSelectAllOption: true
});
});
</script>
<script type="text/javascript">
$(function () {
$('[id*=selectSector]').multiselect({
includeSelectAllOption: true
});
});
</script>
<form runat="server" id="form">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" ScriptMode="Release" ClientIDMode="Static" ViewStateMode="Enabled">
</asp:ScriptManager>
<div style="margin: 10px;">
<asp:Label Style="margin-right: 40px;" ID="YearLabel" Text="Year:" runat="server" AssociatedControlID="selectYear"></asp:Label>
<asp:ListBox ID="selectYear" runat="server" DataValueField="Value" DataTextField="Text" SelectionMode="Multiple" CausesValidation="false"></asp:ListBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" ForeColor="Red"
ControlToValidate="selectYear"
ValidationGroup="yearGroup"
ErrorMessage="Select year."
runat="server">
</asp:RequiredFieldValidator>
</div>
<div style="margin: 10px;">
<asp:Label Style="margin-right: 12px;" ID="PortfolioLabel" Text="Portfolio:" runat="server" AssociatedControlID="selectPortfolio"></asp:Label>
<asp:ListBox ID="selectPortfolio" runat="server" DataValueField="Value" DataTextField="Text" CausesValidation="false"></asp:ListBox>
</div>
<div style="margin: 10px;">
<asp:Label Style="margin-right: 25px;" ID="SectorLabel" Text="Sector:" runat="server" AssociatedControlID="selectSector"></asp:Label>
<asp:ListBox ID="selectSector" runat="server" DataValueField="Value" DataTextField="Text" CausesValidation="false"></asp:ListBox>
</div>
<div>
<asp:Button ID="reportButton" runat="server" OnClick="reportButton_Click" ClientIDMode="Static" Text="Create report" CausesValidation="true" ValidationGroup="yearGroup" />
</div>
<div style="margin-top: 40px;">
<rsweb:ReportViewer runat="server" ID="reporter" Width="100%" ClientIDMode="AutoID" ProcessingMode="Local" BackColor="White" BorderStyle="None" ToolBarItemBorderStyle="None" InternalBorderStyle="None" BorderColor="White" InternalBorderColor="White" ToolBarItemBorderColor="White" AsyncRendering="false"></rsweb:ReportViewer>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
//$("#reportButton").click(function () {
// event.preventDefault();
// alert("Handler for .click() called.");
//});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="Head" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="Title" runat="server">
Besparingen
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="ValidationSummary" runat="server">
</asp:Content>
Code Behind file
public partial class Report : System.Web.Mvc.ViewPage<model>
{
List<string> years = new List<string>();
string sector;
string portfolio;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
selectPortfolio.DataSource = Model.List[0].Portfolios;
selectPortfolio.DataBind();
selectYear.DataSource = Model.List[0].Years;
selectYear.DataBind();
selectSector.DataSource = Model.List[0].Sectors;
selectSector.DataBind();
}
}
protected void reportButton_Click(object sender, EventArgs e)
{
foreach (ListItem item in selectYear.Items)
{
if (item.Selected)
{
years.Add(item.Text);
}
}
sector = selectSector.SelectedItem?.Text ?? string.Empty;
portfolio = selectPortfolio.SelectedItem?.Text ?? string.Empty;
if (years.Count > 0)
{
BesparingenDS.DataTable1DataTable table = new BesparingenDS.DataTable1DataTable();
DataTable1TableAdapter adapter = new DataTable1TableAdapter();
adapter.Fill(table, sector, portfolio, string.Join(",", years));
ReportDataSource datasource = new ReportDataSource("DataSource", (DataTable)table);
System.Security.PermissionSet sec = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
reporter.LocalReport.SetBasePermissionsForSandboxAppDomain(sec);
reporter.LocalReport.ReportPath = "Views\\Besparingen\\BesparingenReport.rdlc";
reporter.LocalReport.DataSources.Clear();
reporter.LocalReport.DataSources.Add(datasource);
reporter.LocalReport.Refresh();
reporter.DataBind();
}
}
}
Thank you for help and sorry for my bad english

How to call an asp control using getElementById() in a javascript function that is included in ScriptManager.RegisterStartupScript

I'm required to use ScriptManager.RegisterStartupScript to run a javascript function while using asp.net's update panel.
My goal is to run my javascript function named Top10 with json parameter called jsonTable, in this function everything is working well aside from var hfield = document.getElementById("<%=hf.ClientID%>"); which is supposedly get the asp.net's hiddenfield control but it keeps returning null.
I reduced the code so that I can get to the point.
c#:
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
dtCurrentTop1O = dsCurrentTop10Winners.Tables["Top 10 Winners"];
string strCurrentTop1O = serializer(dtCurrentTop1O);
ScriptManager.RegisterStartupScript(this.updatePanel1, GetType(), "Javascript",
"javascript:Top10(" + strCurrentTop1O + ");", true);
}
}
Markup:
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="head">
<title></title>
<script src="Scripts/Top10.js" type="text/javascript"></script>
</asp:Content>
<asp: Content ID="Content2" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<asp: ScriptManager ID="scriptManager1" runat="server"></asp: ScriptManager>
<asp: UpdatePanel ID="updatePanel1" runat="server">
<ContentTemplate>
<asp: Panel ID="Panel1" runat="server">
<asp: HiddenField ID="hf" runat="server" />
</asp: Panel>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
javascript: Top10.js
function Top10(jsonTable) {
var chartImg;
var hfield = document.getElementById("<%=hf.ClientID%>");
};
According to your description, the function you're calling is located in the file 'Top10.js'. AFAIK, ASP.NET won't resolve definitions like "<%=hf.ClientID%>" outside of ASP.NET specific files - .js files are delivered to the webclient 'as is' (static content) and not rendered server-side like .aspx files. You'll be able to confirm this when looking at the delivered source in your browsers dev-tools.
You could either place the javascript code directly inside your markup so that the ClientId will be resolved, add an additional hiddenFieldId-parameter to the TopFiveOutsagesCurrentLC function or directly set the HiddenFields content in your Page_Load method.
Example for direct js code in Markup:
<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="head">
<title></title>
<script type="text/javascript">
function TopFiveOutagesCurrentLC(jsonTable) {
var chartImg;
var hfield = document.getElementById("<%=hf.ClientID%>");
};
</script>
</asp:Content>
<asp: Content ID="Content2" runat="server" ContentPlaceHolderID="ContentPlaceHolder1">
<asp: ScriptManager ID="scriptManager1" runat="server"></asp: ScriptManager>
<asp: UpdatePanel ID="updatePanel1" runat="server">
<ContentTemplate>
<asp: Panel ID="Panel1" runat="server">
<asp: HiddenField ID="hf" runat="server" />
</asp: Panel>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
I've answered my question by finding the hiddenfield control and then added it to parameters for the javascript function.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
HiddenField hf = (HiddenField)this.updatePanel1.FindControl("hf");
dtCurrentTop1O = dsCurrentTop10Winners.Tables["Top 10 Winners"];
string strCurrentTop1O = serializer(dtCurrentTop1O);
ScriptManager.RegisterStartupScript(this.updatePanel1, GetType(),
"Javascript",
"javascript:Top10(" + strCurrentTop1O + ","+hf.ClientID+");", true);
}
}

Cannot get filename from AjaxFileUpload using javascript and asp.net

I've tried solving this out and researching for weeks and i still can't get it to work. My code is to simply upload images and then save it in the database without postback.
As of now, I used AjaxFileUpload to upload images. My plan was to get the uploaded filename in AjaxFileUpload using javascript and then store it in a hiddenfield. And then when the admin clicks submit, it will get the value that was stored in the hiddenfield and then save it in the database(using the query that i have created in my code-behind).
The problem is, it will always return empty. I hope you guys can really help me on this one.
Here is the code for the aspx:
<%# Page Language="C#" AutoEventWireup="true"
CodeFile="CreateBrands.aspx.cs" Inherits="Pages_CreateBrands" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="asp"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Music Store</title>
<script src="../Javascript/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="~/Styles/jquery.bxslider.css"/>
<link rel="shortcut icon" type="image/png" href="~/Images/rockSign.png"/>
<script type="text/javascript">
function abc() {
var elem1 = document.getElementById('<%# itemFileUpload1.ID %>').value;
document.getElementById('HiddenInput1') = elem1;
var elem2 = document.getElementById('<%# itemFileUpload2.ID %>').value;
document.getElementById('HiddenInput2') = elem2;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="wrapper">
<h1>Item Image1:</h2>
<br />
<asp:AjaxFileUpload ID="itemFileUpload1" runat="server"
Width="300px" OnUploadComplete="itemUploadImage1"
OnClientUploadComplete="abc"/>
<input type="hidden" id="HiddenInput1" name="HiddenInput" value="" />
<h1>Item Image2:</h2>
<br />
<asp:AjaxFileUpload ID="itemFileUpload2" runat="server"
Width="300px" OnUploadComplete="itemUploadImage2"
OnClientUploadComplete="abc"/>
<input type="hidden" id="HiddenInput2" name="HiddenInput" value="" />
<br/>
<asp:Label ID="lblResult2" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="Button1" runat="server" CssClass="submitButton"
Text="Save Item" OnClick="Button1_Click"/>
</div>
</form>
</body>
</html>
And here is the code for the aspx.cs:
protected void itemUploadImage1(object sender, AjaxFileUploadEventArgs e)
{
string filename = Path.GetFileName(e.FileName);
itemFileUpload1.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename);
}
protected void itemUploadImage2(object sender, AjaxFileUploadEventArgs e)
{
string filename = Path.GetFileName(e.FileName);
itemFileUpload2.SaveAs(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/") + filename);
}
protected void Button1_Click(object sender, EventArgs e)
{
try {
string item_image1 = Request.Form["HiddenInput1"];
string item_image2 = Request.Form["HiddenInput2"];
ConnectionClassGuitarItems.AddStringInstrumentItems(item_image1,item_image2);
lblResult2.Text = "Upload successful!" + item_image1 + " and " + item_image2;
ClearTextFields2();
}
catch (Exception ex)
{
lblResult2.Text = ex.Message;
}
}
Notice the the Button1_Click, I try to access the value of HiddenInput1 and HiddenInput2 but it seems like they are empty.
Why not use a regular asp:FileUpload control and wrap part of your form/code block in an updatepanel to achieve the same desired action as using a AjaxFileUpload control:
<asp:UpdatePanel runat="server" UpdateMode="Always" ID="updPnlName">
<ContentTemplate>
<asp:FileUpload runat="server" ID="fileImport" CssClass="form-control"/>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected void btnUpload_OnClick(object sender, EventArgs e)
{
if (fileImport.HasFile)
{
UploadProcessFile();
}
}
private void UploadProcessFile()
{
var fileName = fileImport.FileName;
//Process the rest of your code below you can also assign the file name to your textbox.
}
You can get your image name like this on aspx file on
<asp:AjaxFileUpload ID="itemFileUpload2" runat="server"
Width="300px" OnUploadComplete="itemUploadImage2"
OnClientUploadComplete="abc"/>
use this script
function abc(sender, args) {
var Imagename = args.get_fileName();
alert(Imagename );
}
this way is very simple hope this help you

Calling javascript Method from Code behind

This code worked in another page
But it's not working in the new page
JS Function to be called:
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<script type="text/javascript">
function myfun() {
alert("test");
}
</script>
</asp:Content>
Html code:
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton CssClass="Link" ID="IMGDetail"
ClientIDMode="Static" runat="server"
ImageUrl="~/Img/Detail.png" Height="19px"
Width="19px" OnClick="IMGDetail_Click" ToolTip="Detail" />
</ItemTemplate>
</asp:TemplateField>
Code behind:
protected void IMGDetail_Click(object sender, ImageClickEventArgs e) {
LinkButton lbtn = (LinkButton) sender;
GridViewRow gvr = (GridViewRow) lbtn.NamingContainer;
Label LabelTicketId = (gvr.FindControl("LBTicketId") as Label);
Session["TicketId"] = LabelTicketId.Text;
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "myfun()", true);
}
I think you need to add following tag in your aspx page.
<asp:ScriptManager ID="ScriptManager" runat="server" />
In Codebehind
ScriptManager.RegisterStartupScript(this, typeof(string), "myfun", "myfun()", true);

Passing child values in Parent with TabPanel

I am having problem with the script of passing values from child to parent with tabpanel (controller). Within that Tab there's a textbox. When I tried to pass a value that within the TabPanel it doesn't work. When I removed the panel it works.
Here the html script from
Parent.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="Form1" runat="server">
<cc1:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0">
<cc1:TabPanel runat="server" HeaderText="TabPanel1" ID="TabPanel1">
<HeaderTemplate>
TabPanel1<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</HeaderTemplate>
<ContentTemplate>
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Button ID="button1" runat="server" OnClick="button1_Click" Text="Button" />
</div>
</ContentTemplate>
</cc1:TabPanel>
<cc1:TabPanel ID="TabPanel2" runat="server" HeaderText="TabPanel2">
</cc1:TabPanel>
</cc1:TabContainer>
</form>
</body>
</html>
and here's the child and Javascript
child.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Child.aspx.cs" Inherits="Child" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="Initialtest" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="Initialtest2" runat="server"></asp:TextBox>
<br />
<%--<input type="button" value="Select" onclick="SetName();" />--%>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
<script type="text/javascript">
function SetName() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("TextBox1");
txtName.value = document.getElementById("Initialtest").value;
var txtName1 = window.opener.document.getElementById("TextBox2");
txtName1.value = document.getElementById("Initialtest2").value;
}
alert("test");
window.close();
}
</script>
</form>
</body>
</html>
the child.aspx.cs (code behind)
public partial class Child : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//protected void Button1_Click(object sender, EventArgs e)
//{
// //
// Button1.Attributes.Add("onclick", "javascript:SetName();");
//}
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "SetName()", true);
}
}
The scenario child must pass the value to textbox1 within that TabPanel. Hoping that someone will help me to resolve the problem.
Done, I resolved this problem.
<script type="text/javascript">
function SetName() {
if (window.opener != null && !window.opener.closed) {
var txtName = window.opener.document.getElementById("TextBox1");
txtName.value = document.getElementById("Initialtest").value;
var txtName1 = window.opener.document.getElementById("TextBox2");
txtName1.value = document.getElementById("Initialtest2").value;
}
alert("test");
window.close();
}
</script>

Categories

Resources