I have a User Control (with Two TextBox and a label) Behind the code of the User Control On Prerender I Use RegisterStartupScript to call a JS function which calls a External JS function Which it calls a WebMethod. Everything works fine until calling the Webmethod. When calling the webmethod using AJAX. The web method does not fires up. I have no idea why. Any help would be appreciated.
SpecificExperienceControl.ascx
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="SpecificExperienceControl.ascx.vb" Inherits="TardyAbsenteeReport.SpecificExperienceControl" %>
<asp:HiddenField ID="hdnID" runat="server" />
<div class="SpecExp">
<asp:TextBox ID="TextBox1" runat="server" CssClass="SpecExp-txtEmpID" ></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Label" CssClass="SpecExp-txtLbl"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" CssClass="SpecExp-txtAcode"></asp:TextBox>
</div>
SpecificExperienceControl.ascx.vb
Public Class SpecificExperienceControl
Inherits System.Web.UI.UserControl
Dim number As Int16 = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Public Property Value As String
Get
Return hdnID.UniqueID
End Get
Set(value As String)
hdnID.Value = value
End Set
End Property
'This function sends the necessary javascript to the page
Protected Sub Me_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
Dim cs = Page.ClientScript
Dim myType = Me.GetType()
'gets one total copy of JQuery
If Not cs.IsClientScriptBlockRegistered(myType, "jquery") Then
cs.RegisterClientScriptBlock(myType, "jquery", GetJQueryInclude())
End If
'gets one total copy of the toggle function in SpecificExp.js
If Not cs.IsClientScriptIncludeRegistered(myType, "helper") Then
cs.RegisterClientScriptInclude(myType, "helper", VirtualPathUtility.ToAbsolute("~/SpecificExperienceControl.js"))
End If
'gets one copy for each user control on the page of the js in the getStartupScript function below
cs.RegisterStartupScript(myType, "regEvents" & Value, getStartupScript(), True)
End Sub
Private Function getStartupScript() As String
Return "$(function(){$('#" & TextBox1.ClientID & "').change(function(){toggle('" &
TextBox1.ClientID & "','" & Label1.ClientID & "','" & TextBox2.ClientID & "')})});"
End Function
'This function get jquery include string
Public Function GetJQueryInclude() As String
Const CurrentJQueryVersion = "2.1.1"
Const formatString = "<!--[if {0}><script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/{1}/jquery.min.js'></script><!{2}[endif]-->"
Return String.Format(formatString, "lte IE 8]", "1.11.1", String.Empty) &
String.Format(formatString, "gt IE 8]", CurrentJQueryVersion, String.Empty) &
String.Format(formatString, "!IE]>--", CurrentJQueryVersion, "--<!")
End Function
End Class
SpecificExperience.aspx
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="SpecificExperience.aspx.vb" Inherits="TardyAbsenteeReport.SpecificExperience" %>
<%# Register Src="~/SpecificExperienceControl.ascx" TagName="SpecExp" TagPrefix="HR" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<hr:SpecExp runat="server"></hr:SpecExp>
</ItemTemplate>
</asp:Repeater>
</asp:Content>
SpecificExperience.aspx.vb (Here I just bind the Repeater to a XML file that generates 25 empty rows)
Public Class SpecificExperience
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xmldatasource2 As XmlDataSource = New XmlDataSource With
{.DataFile = "/App_Data/EmptyRows.xml"}
Repeater1.DataSource = xmldatasource2
Repeater1.DataBind()
End Sub
End Class
SpecificExperienceControl.js
function toggle(txtId, lblname, txtcode) {
$.ajax({
type: "POST",
url: "SearchEmpId.asmx/GetEmployeeName",
data: '{id: "it works"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('#' + lblname).val(data.d);
}
});
}
SearchEmpId.asmx.vb Everything works as it supposed to and then this does not get fired up
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports Newtonsoft.Json
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class SearchEmpId
Inherits System.Web.Services.WebService
<WebMethod()>
Public Shared Function GetEmployeeName(ByVal id As String) As String
Return "itworks"
End Function
End Class
Below is a screen shot of what I'm getting when the request is placed
When I click in Response Body I am seeing this. Why is it not finding the web method ?
Related
I've been struggling for a while with a Javascript/C# issue i have. I've been trying to set a Session variable from Javascript. I tried to use page methods before but it resulted in my javascript crashing.
In the javascript :
PageMethods.SetSession(id_Txt, onSuccess);
And this page method :
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
Page aPage = new Page();
aPage.Session["id"] = value;
return value;
}
I haven't had any success with this. Therefore, i tried to set the value of a textbox from my javascript and put a OnTextChanged event in my c# to set the session variable but the event is not fired.
In the javascript:
document.getElementById('spanID').value = id_Txt;
In the html :
<asp:TextBox type="text" id="spanID" AutoPostBack="true" runat="server"
ClientIDMode="Static" OnTextChanged="spanID_TextChanged"
style="visibility:hidden;"></asp:TextBox>
In the cs :
protected void spanID_TextChanged(object sender, EventArgs e)
{
int projectID = Int32.Parse(dropdownProjects.SelectedValue);
Session["id"] = projetID;
}
Does anyone have an idea as of why none of my events where fired ? Do you have an alternative solution that I could try ?
I found the issue, I didn't have the enableSession = true and i had to use the HttpContext.Current.Session["id"] = value, like stated by mshsayem. Now my event is fired properly and the session variable is set.
First, ensure you have sessionState enabled (web.config):
<sessionState mode="InProc" timeout="10"/>
Second, ensure you have page-methods enabled:
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
Third, set session value like this (as the method is a static one):
HttpContext.Current.Session["my_sessionValue"] = value;
Sample aspx:
<head>
<script type="text/javascript">
function setSessionValue() {
PageMethods.SetSession("boss");
}
</script>
</head>
<asp:ScriptManager ID="sc1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<asp:Button ID="btnSetSession" Text="Set Session Value (js)" runat="server" OnClientClick="setSessionValue();" />
<asp:Button ID="btnGetSession" Text="Get Session Value" runat="server" OnClick="ShowSessionValue" />
<br/>
<asp:Label ID="lblSessionText" runat="server" />
Sample code behind:
[System.Web.Services.WebMethod(true)]
public static string SetSession(string value)
{
HttpContext.Current.Session["my_sessionValue"] = value;
return value;
}
protected void ShowSessionValue(object sender, EventArgs e)
{
lblSessionText.Text = Session["my_sessionValue"] as string;
}
I'm trying to render a list of items from a database as a block of JSON so I can use it on the client side via JavaScript. I thought the best way to do this would be to use a Repeater or ListView to render my items, but I get a "server tag is not well formed" error.
This is my code
<asp:ListView runat="server" ID="rptAddresses" ItemPlaceholderID="plcItems">
<LayoutTemplate>
<script type="text/javascript">
var addressConfig = [
<asp:Placeholder ID="plcItems" runat="server"/>
];
</script>
</LayoutTemplate>
<ItemTemplate>
{
'id': '<asp:Literal runat="server" Text="<%# Eval("AddressID") %>" />',
'name':...
What am I doing wrong?
I'm not sure what you are doing wrong, but it is probably your literal. You can just do this instead:
'id': '<%# Eval("AddressID") %>'
That said there are other alternatives to sending an array to your script:
ClientScriptManager.RegisterArrayDeclaration is built into the framework. Here's an example taken from the linked page:
' Define the array name and values.
Dim arrName As String = "MyArray"
Dim arrValue As String = """1"", ""2"", ""text"""
' Get a ClientScriptManager reference from the Page class.
Dim cs As ClientScriptManager = Page.ClientScript
' Register the array with the Page class.
cs.RegisterArrayDeclaration(arrName, arrValue)
This will render the following array just before the close of your form:
var MyArray = new Array("1", "2", "text");
Personally, I prefer using the JavaScriptSerializer because you can freely serialize basically any object:
Protected Function GetArray() As String
Dim exampleList As New List(Of Pair) From {New Pair(7, 4), New Pair("Foo", "Bar")}
Dim serializer As New Script.Serialization.JavaScriptSerializer()
Return serializer.Serialize(exampleDictionay)
End Function
You can then add it to your .aspx file anywhere you like:
var myArray = <%=GetArray()%>;
which actually renders as an array literal:
var myArray = [{"First":7,"Second":4},{"First":"Foo","Second":"Bar"}];
Of course, you could also do it completely in your aspx markup:
<% Dim serializer As New Script.Serialization.JavaScriptSerializer() %>
var array = <%= serializer.Serialize({"look", "at", "this"})%>;
After much tweaking with all combination of single and double quotes, I eventually solved this by putting the <script> tag in a literal. ie:
<LayoutTemplate>
<asp:Literal runat="server" Text='<script type="text/javascript">' />
var macroConfig = [
<asp:Placeholder ID="plcItems" runat="server"/>
];
$(document).ready(function () {
...
});
<asp:Literal runat="server" Text='</script>' />
</LayoutTemplate>
It seems the parser gets confused with where the script tag ends and the server control tag starts.
I am working on a group project, and am trying to figure out ASP.net (hardly anyone in my group knows it, including me). My job is to make some text box and button such that, when the button is clicked, the text in the text box is processed and posted iff it has <= 140 characters.
I tried to write some jQuery that checks the text in the text box, and then sends it to the server for processing. The server is to save it to database, and post it to page, if it is no more than 140 characters long (this will be checked again).
Unfortunately, I run into this error. I tried to contact my team members, but they are super busy with other issues. Here is my code:
Feed.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Feed.aspx.cs" Inherits="Feed_Feed" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<!-- This is here for test purpose -->
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(
function()
{
$('#TweetButton').click(
function()
{
// get the text from the TweetBox
var status = $('#TweetBox').val();
// if it is 140 characters or less
if (status.length <= 140)
{
var data = JSON.stringify(status);
// send to the server page
$.ajax({
url: '/Feed.aspx.cs',
type: 'POST',
dataType: 'json',
data: data,
success: function(myStatus)
{
$('#MyStatus').html(myStatus);
}
});
}
else
{
alert("Tweet should contain no more than 140 characters");
}
});
});
</script>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<h1>User Feed</h1>
<p>
<input id="TweetBox" type="text" /><input id="TweetButton" type="button" value="button" />
</p>
<div id="MyStatus"></div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="LeftContent" Runat="Server">
</asp:Content>
Feed.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Feed_Feed : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
The C# file is practically empty because I don't know how to handle the data being posted to the page (should it be in Page_Load?) I don't know what to do here...
The code is not going to post data to the asp.net server because you are just using regular HTML elements. In order to convert an html element to asp.net element, you need to use attribute runat="server", so your markup would become :
<input id="TweetBox" type="text" runat="server" /><input id="TweetButton" type="button" value="button" runat="server" />
Alternately, to make the job simpler and have more flexibility on the asp.net controls ( like accessing additional properties ), you should strictly use asp.net core controls. So your new markup would look like :
<asp:TextBox id="TweetBox" runat="server"></asp:TextBox>
<asp:Button id="TweetButton" runat="server"></asp:Button>
In order to trigger a click event to post data onto the server ( codebehind ), you need to add the attributes OnClick to your button.
<asp:Button id="TweetButton" runat="server" OnClick="TweetButton_Click"></asp:Button>
In the codebehind (*.aspx.cs), you need to handle the event triggered by the button and check for the length of the text.
public partial class Feed_Feed : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void TweetButton_Click(object sender, EventArgs e)
{
if(TweetBox.Text.Length <= 140)
{
// Save data in the database.
}
}
}
UPDATE :
To work with ajax, you would need asp.net controls, so your markup would be
.ASPX =>
<input id="TweetBox" type="text" />
<input id="TweetButton" type="button" value="button" />
<script>
$().ready(function()
{
$('#TweetButton').click(function(){
// if it is 140 characters or less
if (status.length <= 140)
{
// send to the server page
$.ajax({
url: '/Feed.aspx/SubmitTweet',
type: 'POST',
dataType: 'json',
data: "{'tweet':'" + $('#TweetBox').val() + "'}",
success: function(myStatus)
{
$('#MyStatus').html(myStatus.d);
},
error : function(er)
{
}
});
}
else
{
alert("Tweet should contain no more than 140 characters");
}
});
});
</script>
.ASPX.CS ( code-behind ) =>
[WebMethod]
public static string SubmitTweet(string tweet)
{
// dummy function :
return DataSubmit(tweet) ? "Data Was submitted" : "Error while submitting data";
}
public bool DataSubmit(string data)
{
//call db connection and save the tweet
// if successful , return true else false
}
I have a button in my updatepanel and I'm trying to call a javascript function (after it does it's processing).
I put this code inside the Page_Load:
Dim cstype As Type = Me.GetType()
Dim cs As ClientScriptManager = Page.ClientScript
cs.RegisterStartupScript(cstype, "modalScript", "jsModal('" + msg + "');", True)
keywordSearch.Attributes.Add("onclick", "jsModal('" + msg + "');")
Client Side javascript:
function showModal(msg) {
$("#modal-content, #modal-background, #modal-close").toggleClass("active");
var returnString = msg;
$('#modal-content div').each(function (index) {
$(this).html(returnString);
});
}
How do I pass the values I gather from the server side click event into the javascript function?
I suppose your question is about webform. In this case try this in the aspx
<script type="text/javascript">
$(document).ready(function() {
$("#buttonTest").click(function () {
$("#<%= hiddenField.ClientID%>").val("TEST");
});
});
</script>
<asp:HiddenField runat="server" ID="hiddenField" />
<button id="buttonTest">
Change value hidden field
</button>
<asp:Button runat="server" Text="POST" ID="postButton" />
And this in the CodeBehind
Private Sub postButton_Click(sender As Object, e As EventArgs) Handles postButton.Click
YourLogic(hiddenField.Value)
End Sub
In my Vb .net code-behind (Visual Studio 2005), in a method fired by click event:
hdnUrl and hdnParameters are hiddenFields
Protected Sub btnExample_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExample.Click
.
.
.
hdnUrl.Value = "Mypage.aspx?i=" & SomeCveDefinedInCodeBehind.Tostring & "&u=" & OtherCveDefinedInCodeBehind.Tostring
hdnParameters.value = "resizable: no; scroll: no; center: yes; dialogHeight: 525px; dialogWidth:750px; status: no;"
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType, DateTime.Now.ToString, "<script type='text/javascript'> ShowWindow(); </script>", False)
.
.
.
In my page:
<asp:Content ID="Content3" ContentPlaceHolderID="cph3" runat="Server">
.
.
.
<asp:HiddenField ID="hdnUrl" runat="server" Value="" />
<asp:HiddenField ID="hdnParameters" runat="server" Value="" />
<asp:HiddenField ID="hdnResult" runat="server" Value="" />
<script language="javascript" type="text/javascript">
function ShowWindow()
{
alert('i am here');
var url = document.getElementById('<%= hdnUrl.ClientID %>').value;
var Parameters = document.getElementById('<%= hdnParameters.ClientID %>').value;
//For test:
alert(url); //------ i need to get here: "My page.aspx?...", but i always get: ""
alert(parameters); // i need to get here my parameters, but i always get: ""
.
.
.
var dialogWin = window.showModalDialog(url, "some text", parameters); //showModalDialog window, will return a data that i need in CodeBehind
document.getElementById('<%= hdnResult.ClientID %>').value=dialogWin.result;
//Then i could manage the result, in code-behind
}
</script>
</asp:Content>
Only if in the hidden field definition i set:
<asp:HiddenField ID="hdnUrl" runat="server" Value="My text" />
i can get this text in the javascript alert, but i need define the text in code-behind
Thanks for your Help and suggestions.
is there another way for pass url and parameters, to the window.showModalDialog???
or another way for get the result of the window.showModalDialog in code.behind???
Watch the casing on your Parameters variable. Also try using RegisterStartupScript instead of RegisterClientScriptBlock. The difference is the former will put your javascript at the bottom of the page while the latter puts it at the top. This will cause the script to run before the document it fully loaded.
ScriptManager.RegisterStartupScript(Page, Page.GetType, DateTime.Now.ToString, "<script type='text/javascript'> ShowWindow(); </script>", False)