calling C# function from aspx code - c#

I want to call a C# function from aspx code when I type in something in the text box. How can I call a C# function from aspx code on a key down event of a text box.?

Make a Key Down Event
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
Function1();
}
Function
private void Function1()
{
}

Try Jquery ajax -
var ListPostalCode = ["12345"];
var PostalCodeJsonText = JSON.stringify({ list: ListPostalCode });
$.ajax({
type: "POST",
url: "JobManagement.aspx/FindLocation",
data: PostalCodeJsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
});
C# WebMethod -
[System.Web.Services.WebMethod()]
public static string FindLocation(List<string> list)
{
try{
string LocationInfo = "";
HttpWebRequest FindLocationreq = (HttpWebRequest)WebRequest.Create("http://ziptasticapi.com/" + list[0]);
FindLocationreq.Method = "GET";
using (WebResponse Statusresponse = FindLocationreq.GetResponse())
{
using (StreamReader rd = new StreamReader(Statusresponse.GetResponseStream()))
{
LocationInfo = rd.ReadToEnd();
}
}
return LocationInfo;
}
catch (Exception ex)
{
return ex.Message;
}
}
Reference 1
Reference 2
Reference 3

Try like this
<asp:TextBox ID="TextBox1" clientidmode="Static" runat="server" onkeypress="return EnterEvent(event)"></asp:TextBox>
JS:
function EnterEvent(e) {
if (e.keyCode == 13) {//if enter key is pressed condition
__doPostBack('<%=Button1.UniqueId%>', "");
}
}
C#:
protected void Button1_Click(object sender, EventArgs e)
{
}

$("#target").keypress(function() {
var value=$("#target").val();
$.ajax({
type: "POST",
url: "../Webservices/yourwebservice.asmx/webmethodName",
data: "{value: " + value + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
alert(result.d);
}
);
});
you can make the call to your webmethod like this on key press.thanks

Here's one way:
ASPX:
<asp:TextBox ID="MyTextBox" ClientIDMode="Static" runat="server" />
JS:
$(function() {
$('#MyTextBox').keyup(function() {
var jsonObj = { c: $(this).val() };
$.ajax({
type: 'POST',
url: 'webservice.aspx/MyCSharpFunction',
data: JSON.stringify(jsonObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
}
});
});
});
C# (webservice.aspx in this example):
public partial class webservice : System.Web.UI.Page
{
[WebMethod]
public static string MyCSharpFunction(string c)
{
return "You typed " + c;
}
}

Related

How to call async on button click?

Im doing like below to call asyn on clikc
private List<SuggestedItemsInput> suggestedItemAsync()
{
OHDWebService OHDService = new OHDWebService();
List<SuggestedItemsInput> suggestedItemsList = OHDService.SaveSuggestedItems(ViewState["Body"].ToString(), hfdOrderRecordID.Value);
return suggestedItemsList;
}
onclick
protected async void imgbtnClaim_Click(object sender, EventArgs e)
{
try
{
Task<List<SuggestedItemsInput>> task = new Task<List<SuggestedItemsInput>>(suggestedItemAsync);
task.Start();
lblError.Text = "Please Wait. Proccessing...";
List<SuggestedItemsInput> suggestedItems = await task;
if (suggestedItems.Count > 0)
{
but it is blocking UI, and thouswing error like below
How can achieve this?
Create a webmethod like this:
[WebMethod]
public async Task Yourmethod(string value)
{
value = "abc";
return value;
}
And then from your front end use jquery to hit this method like this:
<script>
$(fucntion(){
$.ajax({
type: "POST",
url: "..../Yourmethod",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) { }
});
});
Hope it helps.

Ajax Jquery not return the URL after using ActionLink in MVC

I got a scenario:
Here's my ActionResult when ActionLink was Clicked
public PartialViewResult ViewHit(string id, string recordid,string statusSelect,string statusHitSelect)
{
//some code here....
}
The ActionLink where to post after the Button was clicked:
public ActionResult SaveUpdate(String statusSelect, string statusHitSelect)
{
return PartialView("ViewHitList");
}
Here's the button:
<input type="button" value="Save" id="savehit"/>
and Here's my Ajax:
$("#savehit").on('click', function () {
//alert("Button was click!");
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
//url: "SelectUpdate?statusSelect=" + statusSelect + '&statusHitSelect=' + statusHitSelect,
url: "SaveUpdate",
data: "{'statusSelect':'" + statusSelect + "','statusHitSelect':'" + statusHitSelect + "'}",
//data:null,
success: function (response) {
if (response != null && response.success) {
//InformationMessageSuccess(response.responseText);
alert("success");
} else {
// DoSomethingElse()
//InformationMessageFailed(response.responseText);
alert("not success");
}
},
});
});
The problem is, when i hit the save button using debug mode the ActionResult called was the ViewHit instead of SaveUpdate.
I am wondering why is it happen?
Any great idea is highly appreciated.
You can try to avoid default action of the event by using event.preventDefault()
$("#savehit").on('click', function (event) {
event.preventDefault();
//alert("Button was click!");
$.ajax({
type: "post",
contentType: "application/json; charset=utf-8",
//url: "SelectUpdate?statusSelect=" + statusSelect + '&statusHitSelect=' + statusHitSelect,
url: "#Url.Action("SaveUpdate", "Home")",
data: "{'statusSelect':'" + statusSelect + "','statusHitSelect':'" + statusHitSelect + "'}",
//data:null,
success: function (response) {
if (response != null && response.success) {
//InformationMessageSuccess(response.responseText);
alert("success");
} else {
// DoSomethingElse()
//InformationMessageFailed(response.responseText);
alert("not success");
}
}
});
});
Add the [HttpPost] attribute to the SaveUpdate action
In the ajax, change the URL to url: "ControllerName/SaveUpdate"
Since you are expecting a boolean result (JSON) back to your page as the ajax response, simply return a jsonResult (true/false)
SaveUpdate is not post type please add attribute [HttpPost] at the top of the controller method like
[HttpPost]
public ActionResult SaveUpdate(String statusSelect, string statusHitSelect)
{
return PartialView("ViewHitList");
}
I have changed the ajax call like bellow and it the SaveUpdate method. Bellow is the ajax call.
$(document).ready(function () {
$("#savehit").on('click', function () {
var statusSelectData="statusSelect";
var statusHitSelectData="statusHitSelect";
var postData = {
statusSelect: statusSelectData,
statusHitSelect: statusHitSelectData
}
//alert("Button was click!");
$.ajax({
type: "POST",
url: "/Home/SaveUpdate",
data: postData,
//data:null,
success: function (response) {
if (response != null && response.success) {
//InformationMessageSuccess(response.responseText);
alert("success");
} else {
// DoSomethingElse()
//InformationMessageFailed(response.responseText);
alert("not success");
}
},
});
});
});

Pass variable from jquery to code behind

<asp:Button ID="Button1" runat="server" Text="Submit" />
<script>
$(document).ready(function () {
$("#Button1").click(function () {
var list = [];
var a= $("#TextBox1").val();
var b= $("#TextBox2").val();
var count = a* b;
list.push('test');
for (var i = 1; i <= count; i++) {
var item = $("#DropDownList_" + i + "_").find(":selected").text();
list.splice(i, 0, item);
console.log(list.join());
alert(list[i]);
}
});
});
</script>
Hello guys first time at the stack! I have this jquery code that get all choices of dropdown list and store it in array.
I want pass this array to c# so I can store the values in DB, please help.
You can simply do this using jQuery ajax:-
var dataToSend = { "Data": list};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/SaveData",
data: JSON.stringify(dataToSend),
success: function (msg) {
//success data if any
},
error: function (msg) { //handle error here }
});
Add this method in your page behind (Default.aspx.cs):-
[WebMethod]
public static void SaveData(string[] Data)
{
//Save data to DB
}

Unable to call aspx page web method using jquery ajax call?

Here is my ajax call
$(document).ready(function () {
$("#btnSubmit").click(function () {
alert("I am in ?");
$.ajax({
type: "POST",
url: "TestNew2.aspx/DisplayData",
data: "{}",
contentType: "application/x-www-form-urlencoded",
dataType: "text",
//success: function (msg) {
// // Replace the div's content with the page method's return.
// $("#btnSubmit").text(msg.d);
// alert(msg.d);
//}
success: function (result, status, xhr) {
document.getElementById("lblOutput").innerHTML = xhr.responseText
},
error: function (xhr, status, error) {
alert(xhr.error);
}
});
});
});
and my Web method[WebMethod]
public static string DisplayData()
{
return DateTime.Now.ToString();
}
Getting aspx page when trying to call web method on aspx page.Here is the jQuery code
Can any one point out what may be wrong.Because the web method is not getting called.
Try Like
$.ajax
({
url: " URL",
data: "{ 'name' : 'DATA'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
alert(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
OR
jQuery.ajax({
type: "POST",
url: "Login.aspx/checkUserNameAvail",
contentType: "application/json; charset=utf-8",
data: "{'iuser':'" + userid + "'}",
dataType: "xml",
success: function (msg) {
$(msg).find("Table").each(function () {
var username = $(this).find('UserName').text();
if (username != '') {
//window.location.replace('/iCalendar.aspx');
alert('This username already taken..');
$("#reguser").val('');
$("#reguser").focus();
}
else {
}
});
},
error: function (d) {
}
});
.CS
[WebMethod(enableSession: true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public static string checkUserNameAvail(string iuser)
{
try
{
iCalendarClass iC = new iCalendarClass();
DataSet ds = iC.checkUserNameAvail(iuser);
return (ds.GetXml());
}
catch
{
return null;
}
}

How to call Web Method using Jquery Ajax

I am using ajax to call a [WebMethod].But it doesn't Works.Code i used is
ASPX page
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/CandidateManagement.aspx/GetCurrentDateTime") %>',
data: '{name: "' + document.getElementById("lbcb5").innerHTML + '" }', Value
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
Aspx.cs page
[WebMethod]
public static string GetCurrentDateTime(string name)
{
return "Hey! " + name + Environment.NewLine + "The Current Date & Time is: "
+ DateTime.Now.ToString();
}
Thanks in advance
you don't need quotes on data, do like this:
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/CandidateManagement.aspx/GetCurrentDateTime") %>',
data: {name: document.getElementById("lbcb5").innerHTML},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
alert(response)
},
failure: function (response) {
alert(response.d);
}
});
Did you add a ScriptManager in you aspx page?
I think you should try to add it with the attribute EnablePageMethods="true"
try this:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
"When i use ScriptManager shows an error Only one instance of a ScriptManager can be added to the page."
when this type of error is thrown, then use scriptmanager proxy
<ajax:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
</ajax:ScriptManagerProxy>
--------------************DEFAULT.ASPX************--------------
<script type="text/javascript">
function YolAl(yol) {
deger='<%=ResolveUrl("~/'+ yol +'") %>'
return deger;
}
</script>
*******************------USERCONTROL CALL JS-------************************
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
deger += 1;
RepeaterFnc("BaglantiItem.ascx", deger, "BagListDiv", YolAl('Default.aspx/AddGadGets'));
}
});
$(document).ready(function () {
deger += 1;
RepeaterFnc("DurumGuncelle.ascx", deger, "BagListDiv", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("IlanlarTab.ascx", deger, "SolDivAlanId", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("BaglantiItem.ascx", deger, "BagListDiv", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("Top10TakipEt.ascx", deger, "SagDivFavoriId", YolAl('Default.aspx/AddGadGets'));
RepeaterFnc("Top10Ilanlar.ascx", deger, "SolDivAlanId", YolAl('Default.aspx/AddGadGets'));
});
function TakipEtYenileFnc() {
$('#SagDivFavoriId').html('');
RepeaterFnc("Top10TakipEt.ascx", deger, "SagDivFavoriId", YolAl('Default.aspx/AddGadGets'));
}
function RepeaterFnc(usercontrol, deger, DivName,FuncName) {
$('#ajaxloading').show();
var NextId = deger;
$.ajax({
url: FuncName,
type: "POST",
data: "{usercontrol:'" + usercontrol + "', NextId:'" + NextId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
OnSuccess1(msg, DivName);
},
error: function (msg) { OnError1(DivName); }
});
deger = parseInt(deger + 1);
}
function OnSuccess1(data, DivName) {
$("#" + DivName).html($("#" + DivName).html() + data.d);
$('#ajaxloading').hide();
}
function OnError1(divname) {
return false;
$("#" + divname).html("Error!");
}

Categories

Resources