Below is the my ajax request
function sendData() {
var formdata = new FormData();
var fileUpload = $("#txtUploadFile").get(0);
var files = fileUpload.files;
for (var i = 0; i < files.length; i++) {
formdata.append(files[i].name, files[i]);
}
formdata.append("PaymentDate", new Date());
$.ajax({
url: 'CCA_Form.aspx/SendData',
type: 'POST',
data: formdata,
contentType: false,
processData: false,
success: function () {
alert("Data Added Successfully");
},
error: function () {
alert("Error while inserting data");
}
});
}
and my server method is like this
[WebMethod]
public static string SendData()
{//break point here
// code
return "return data";
}
the ajax method always showing success message and webmethod not hitting in server side. Could you help me what i missed in my code?
Thanks in advance.
Add a scriptmanager into your page with EnablePageMethods="True"
In C#:
[WebMethod]
public static string SendData(DateTime date)
{//break point here
// code
return "return data";
}
In aspx
<asp:ScriptManager ID="ScriptManagerMain"
runat="server"
EnablePageMethods="true"
ScriptMode="Release"
LoadScriptsBeforeUI="true">
</asp:ScriptManager>
In javascript
PageMethods.SendDate(new Date(),function(response){
// success
});
And use <asp:AsyncFileUpload .. for uploading file asyncly
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="xc" %>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<xc:AsyncFileUpload OnClientUploadError="uploadError"
OnClientUploadComplete="uploadComplete" runat="server"
ID="AsyncFileUpload1" Width="400px" UploaderStyle="Modern"
OnUploadedComplete = "FileUploadComplete"
/>
<asp:Label id="lblMsg" runat="server" />
</form>
Also
protected void FileUploadComplete(object sender, EventArgs e)
{
string filename = System.IO.Path.GetFileName(AsyncFileUpload1.FileName);
AsyncFileUpload1.SaveAs(Server.MapPath("Uploads/") + filename);
}
And js
<script type = "text/javascript">
function uploadComplete(sender) {
$get("<%=lblMsg.ClientID%>").innerHTML = "File Uploaded Successfully";
}
function uploadError(sender) {
$get("<%=lblMsg.ClientID%>").innerHTML = "File upload failed.";
}
Related
HTML code below is a simplified code taken from c-sharpcorner. I would like to modify this and transfer all logic in code behind. What I would like to know is how to convert the function, AddEmp, if I transfer this to btnSave's Click method. This is my first time using REST API and still learning to use it. Any advise is greatly appreciated.
protected void btnSave_Click(object sender, EventArgs e)
{
}
HTML
<html>
<head runat="server">
<title>Code snippet taken from Vithal Wadje's article</title>
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
function AddEmp() {
var Emp = {};
Emp.FirstName = $("#txtFirstName").val();
Emp.LastName = $("#txtLastName").val();
Emp.Company = $("#txtCompany").val();
$.ajax({
url:"<%=Page.ResolveUrl("/api/Emp/AddEmployees")%>",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(Emp),
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});
}
$(document).ready(function ()
{
$("#btnSave").click(function (e) {
AddEmp();
e.preventDefault();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
First Name <asp:TextBox runat="server" ID="txtFirstName" />
<br />
Last Name <asp:TextBox runat="server" ID="txtLastName" />
<br />
Company <asp:TextBox runat="server" ID="txtCompany" />
<br />
<asp:Button Text="Save" runat="server" ID="btnSave" />
</form>
</body>
</html>
I have to pass bulk array values to code behind (cs) using ajax i had researched a lot and used this code but it didnot worked for me below is the code that i used what i need is i need to pass bulk array values in code behind(cs) using ajax
JS
<head runat="server">
<title></title>
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace PassingValueFromJavascriptToCs
{
public partial class WebForm3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static void done(string[] ids)
{
String[] a = ids;
// Do whatever processing you want
// However, you cannot access server controls
// in a static web method.
}
}
}
First of all the button for aspx is sending your aspx form to a postback so that you would need to change the aspx like this
<script>
function foo() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" UseSubmitBehavior="false" OnClientClick="return foo();" />
</div>
</form>
</body>
The reason the foo method returns false that you dont want to make your button start a postback. I also added another property UseSubmitBehavior="false" to guarantee it.
The scripts section i changed the values object to a real array and then when sending data , i converted it to json with values object inside. This code will work in your example just fine
Edit : For the working version on my tests
The aspx page (trimmed details to the master page)
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script>
function test() {
var values = ["1,", "2", "3"];
// Make the ajax call
$.ajax({
type: "POST",
url: "Default.aspx/test", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ arr: values }),
dataType: "json",
success: function (result) {
debugger;
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
return false;
}
</script>
<asp:Button ID="Button3" UseSubmitBehavior="false" OnClientClick="return test();" runat="server" Text="Deneme" />
</asp:Content>
The RouteConfig and original method
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
//settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
[WebMethod]
public static void test(string[] arr)
{
}
Well at least one issue is your url is "Default.aspx/Done" but the method appears to be on WebForm3.aspx/Done.
What actually happens with your code? Does it error?
jQuery autocomplete selection with mouse click doesn't get selected in IE. The textbox (that is inside GridView, EditItemTamplate) still post back with the typed in text box not the selected value from dropdown list in IE. It works fine in Google and Firefox.
This code is in my content page. When I type a letter in the texbox, autocomplete give me a list of options. If I use 'up' or 'down' arrow and select the option, it populate my textbox correctly. But if I choose an option with a mouse click, then it doesn't populate my textbox with the option I chose, it just posts back with whatever I typed in the textbox.
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="BlindKeyVerification.aspx.cs" Inherits="Test.Administration.BlindKeyVerification" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link href="../Styles/jquery-ui.css" rel="stylesheet" />
<link href="../Styles/jquery-ui.min.css" rel="stylesheet" />
<script src="../Scripts/jquery.js" type="text/javascript"></script>
<script src="../Scripts/jquery-ui.js" type="text/javascript"></script>
<script src="../Scripts/jquery-ui.min.js" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
$(document).ready(function () {
$("[id*=txtGridCode]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("/Administration/priceCodeService.asmx/getPriceCodeArray") %>',
data: "{ 'priceCode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item,
val: item.split('-')[0]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
$("[id*=txtGridCode]").autocomplete({
select: function (event, ui) {
$this = $(this);
setTimeout(function () {
$("[id*=txtGridCode]").val(ui.item.val);
}, 1);
}
});
});
function InitializeRequest(sender, args) {
$("*").css("cursor", "wait");
}
function EndRequest(sender, args) {
$("*").css('cursor', 'auto');
}
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
//if ((evt.keyCode == 13) && (node.type == "text")) { return false; } //Stop return Key from Posting the page
if ((evt.keyCode == 8) && (node.type == "select-one")) { return false; } //dropdown box backspace stop backpage
}
document.onkeypress = stopRKey; //Firefox
document.onkeydown = stopRKey; //i.e.
</script>
Some parts of the textbox inside the GridView:
BlinkKeyVerfication.aspx
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField HeaderText="Code">
<ItemTemplate>
<asp:Label ID="lblCode" runat="server" ForeColor="Red" Font-Size="Smaller">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGridCode" runat="server" OnTextChanged="txtGridCode_TextChanged" AutoPostBack="true"></asp:TextBox>
</EditItemTemplate>
<ItemStyle Font-Size="Smaller" />
</asp:TemplateField>
</Columns>
</asp:GridView>
priceCodeService.asmx.cs
public partial class WebForm1 : System.Web.UI.Page
{
public List<string> getPriceCodeArray(string priceCode)
{
List<string> doc = new List<string>();
string CSConn = "Server=CourtData;Initial Catalog= CourtSupport; Integrated Security = SSPI";
using (SqlConnection conn = new SqlConnection(CSConn))
{
using (SqlCommand comm = new SqlCommand("SELECT priceCode, priceText FROM tblpriceCodeExtract WHERE priceCode like #priceCode + '%'", conn))
{
SqlParameter parameter_code = new SqlParameter();
parameter_code.ParameterName = "#priceCode";
parameter_code.Value = priceCode;
comm.Parameters.Add(parameter_code);
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
while (rdr.Read())
{
//string doccode = rdr["priceCode"].ToString();
//string codetext = rdr["priceText"].ToString();
//if (codetext.Length > 30)
// codetext = codetext.Substring(0, 29) + "...";
//doc.Add(string.Format("{0}-{1}", doccode, codetext));
doc.Add(rdr["priceCode"].ToString());
}
}
}
return doc;
}
}
Because of compatibility view, my code was not working properly, our site is in compatibility view.
In my aspx content page head section I had following code, but it don't had any use because my masterpage code was blocking it
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
then i removed that code from content page and I added following code in my .cs file
protected void Page_Load(object sender, EventArgs e)
{
if (Header.Controls[1].GetType() != typeof(System.Web.UI.HtmlControls.HtmlMeta))
{
System.Web.UI.HtmlControls.HtmlMeta meta = new System.Web.UI.HtmlControls.HtmlMeta();
meta.HttpEquiv = "X-UA-Compatible";
meta.Content = "IE=edge";
this.Header.Controls.AddAt(1, meta);
}
Now my code is working fine in all browser. Now I don't need any more select event in my code. so i removed it.
I am trying to apply the captioned feature in my project and decided to try it out to see how it works. But while testing it, it shows an Client script error with a message Undefined when I scroll to the bottom of the page. I do not know what I did wrong in my code and I don't know how to get it to work. I am hoping someone helps me out of this. Below is the code:
Repeater
<div id="dvCampaigns">
<asp:Repeater ID="rptUsers" runat="server">
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width: 200px; height: 100px;
border: dashed 2px #04AFEF; background-color: #B0E2F5">
<tr>
<td>
<b><u><span class="campaignname">
<%# Eval("CampaignName") %></span></u></b>
</td>
</tr>
<tr>
<td>
<b>Description: </b><span class="description">
<%# Eval("Description") %></span><br />
<b>ID: </b><span class="campaign-id">
<%# Eval("CampaignID") %></span><br />
<b>Date Created: </b><span class="datecreated">
<%# Eval("CreatedOn")%></span><br />
</td>
</tr>
</table>
<br />
</ItemTemplate>
</asp:Repeater>
</div>
<div>
<img id="loader" alt="" src="../Images/loading.gif" style="display: none" />
</div>
Code-Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
rptCampaigns.DataSource = GetUserData(1);
rptCampaigns.DataBind();
}
}
public static TList<POLLice.Entities.Campaigns> GetCampaignData(int pageIndex)
{
int totalData;
var items = new CampaignsService().GetAll(pageIndex, 10, out totalData);
return items;
}
[WebMethod]
public static string GetCampaigns(int pageIndex)
{
var dataset = GetUserData(pageIndex).ToDataSet(true);
return dataset.GetXml();
}
jQuery Script
<script type="text/javascript">
var pageIndex = 1;
var pageCount;
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
GetRecords();
}
});
function GetRecords() {
pageIndex++;
if (pageIndex == 2 || pageIndex <= pageCount) {
$("#loader").show();
$.ajax({
type: "POST",
url: "UserProfile/Default.aspx/GetCampaigns",
data: '{pageIndex: ' + pageIndex + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
},
error: function(response) {
alert(response.d);
}
});
}
}
function OnSuccess(response) {
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
var campaigns = xml.find("Campaigns");
campaigns.each(function() {
var campaign = $(this);
var table = $("#dvCampaigns table").eq(0).clone(true);
$(".campaignname", table).html(campaign.find("CampaignName").text());
$(".description", table).html(campaign.find("Description").text());
$(".campaign-id", table).html(campaign.find("CampaignID").text());
$(".datecreated", table).html(campaign.find("CreatedOn").text());
$("#dvCampaigns").append(table).append("<br />");
});
$("#loader").hide();
}
</script>
Many Thanks.
In your ajax you have this line:
url: "UserProfile/Default.aspx/GetCampaigns",
Did you remove the full path including http for this post or is that the way it is in your code? That needs a relative or absolute path to the web method. Also when calling web methods with ajax you need to use:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] //or whatever your return format is
[WebMethod]
I need to get javascript values on code behind in c#.I know i can use hidden field but there is no server control on page for postback.Please tell me how can get vales in code behind.
Here is my code:
<html>
<head>
<title>Facebook Get Logged in User Details UserName,Email,Profile Image</title>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// Load the SDK Asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: 'APPID', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var uid = "http://graph.facebook.com/" + response.authResponse.userID + "/picture";
FB.api('/me', function (me) {
document.getElementById('auth-displayname').innerHTML = me.name;
document.getElementById('myJSString').value = me.name;
alert(document.getElementById('myJSString').value);
document.getElementById('Email').innerHTML = me.email;
document.getElementById('profileImg').src = uid;
// document.getElementById('ctl00_CPHDefault_tcTPS_TPProd_ctl01_tcProduction_TPNewTitlesStatus_ChangedRowsIndicesHiddenField').value = uid;
// alert('yyy');
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div id="Result" class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login</div>
</div>
<div id="auth-loggedin" style="display: none">
Name: <b><span id="auth-displayname"></span></b>(logout)<br />
Email: <b><span id="Email"></span></b><br />
Profile Image: <img id="profileImg" />
<form runat="server">
<asp:HiddenField runat="server" id="myJSString" />
</form>
</div>
</div>
</body>
</html>
You can see there is no server control so how i can get NAME,UID variables in code behind.
Thanks
You can use a hiddenfield server control assign the values you need to it in javascript and assess it on server side. If you do not want post back then you can use jQuery ajax to send values.
Html
<asp:hiddenfield id="ValueHiddenField" runat="server"/>
Javascript
document.getElementById('ValueHiddenField').value = "yourValue";
Code behind
string yourValue = ValueHiddenField.Value;
Using jQuery ajax and web method to send values to code behind, you can find nice tutorial over here.
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: {'yourParam': '123'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Code behind
[WebMethod]
public static void YourMethod(string yourParam)
{
//your code goes here
}
I would investigate the use of ASP.NET AJAX Page Methods, because they allow for script callable stand-alone web services that live in an .aspx page, like this:
Page Method in your code-behind file (call it default.aspx for discussion's sake):
[WebMethod]
public static string SaveData(string name, string uid)
{
// Logic here to do what you want with name and uid values (i.e. save to database, call another service, etc.)
}
jQuery call to default.aspx's SaveData method:
$.ajax({
type: "POST",
url: "default.aspx/SaveData",
data: "{'name':'John', 'uid':'ABC123'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
Notes: ASP.NET AJAX Page Methods automatically encode their response to JSON so you will not see any JSON serialization in the code-behind or any serialization logic at all.
For more information about ASP.NET AJAX Page Methods check out Using jQuery to directly call ASP.NET AJAX page methods
You can use following method:
<script language="javascript" type="text/javascript">
function returnString() {
var val = 'sampleValue';
return val;
}
</script>
C# Code to get the return value of the above function:
ClientScript.RegisterClientScriptBlock(this.GetType(), "alertScript", "<script language="javascript">var a=returnString();alert(a);</script>");
Or simply as Adil said, can use hidden field and assign value:
<asp:HiddenField ID="hField" Value="0" runat="server" />
<asp:Button ID="Button1" runat="server" OnClientClick="returnString();"
Text="Button" onclick="Button1_Click" />
script for assigning value:
<script language="javascript" type="text/javascript">
function returnString() {
debugger;
document.getElementById("hField").value = "sampleValue";
}
</script>