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.
Related
I have this code(JQuery) in my View:
$("form").submit(function (e) {
e.preventDefault();
var form = this;
var link = '#Url.Action("Action", "Controller")';
var args = {
MyFVal: MyFVal.val(),
MySVal: MySVal.val()
};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
alert(data.acces);
if (data.acces) {
AllEnable();
form.submit();
}
else {
alert(data.erromessage);
}
},
error: function () {
alert("Error. Kontaktujte správce.");
}
});
});
When I gets submitted then I have this if in my save action.
if (Request.Form.ContainsKey("Insert"))
{
// do code that is supposed to run
}
else if (Request.Form.ContainsKey("Edit"))
{
// do another code
}
My problem is that because I submitted form by JQuery this if and elseif never gets executed.
Thanks for any help!
You might want to pass value for your requirements in Action condition. See operationType sample parameter
var obj = {
UniqueId: modelUniqueId.val(),
Name: modelName.val(),
operationType: $("[name=operationType]").val()
};
$.ajax({
type: "POST",
url: '/hrms/Class/Index',
data: obj,
success: function (result) {
if (result.success == true) {
createAndProcessPageAlert("success", result.message);
}
else {
createAndProcessPageAlert("error", result.message);
}
And in your Controller \ Action
[HttpPost]
public JsonResult Index(string operationType, ClassModel model)
{
var result = new HttpResponseModel<ClassModel>();
var user = Request.GetUserProfile();
if (operationType == "add")
I am trying to make an ajax call using jQuery to C# method.
$(".imgDbAttachment").on("click", function (e) {
debugger;
var fileName = $(this).attr('data-attchment-id');
fileExt = $(this).attr('data-attchment-type');
loadAjaxImage(fileName, fileExt);
});
function loadAjaxImage(id,type) {
$.ajax({
type: "POST",
url: "../CommonDesign/Test.aspx/GetImage",
data:{
'attachmentId': id,
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
}
}).done(function (data) {
if (console && console.log) {
console.log(data);
}
});
}
public partial class Test: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var str = this.Request.Url;
}
[WebMethod]
public string GetImage(string attachmentId)
{
return "hello";
}
But when I am making ajax call,the control is hitting the PageLoad() & not the GetImage() & this in turn returning entire aspx page content
check these links,
$.ajax Returning HTML of the page instead of results
some other as well
But still the same issue.
Any suggestion/highly appreciated.
Make GetImage() static
[WebMethod]
public static string GetImage(string attachmentId)
{
return "hello";
}
More reading here
It looks like you are doing a Post as well when you click the button. It is best to add a
return false;
to the last line of your function
$(".imgDbAttachment").on("click", function (e) {
debugger;
var fileName = $(this).attr('data-attchment-id');
fileExt = $(this).attr('data-attchment-type');
loadAjaxImage(fileName, fileExt);
return false;
});
The code is:
$.ajax({
type: "POST",
url: '#Url.Action("getFilterActiveData")',
dataType: "json",
mtype: "post",
traditional: true,
data: {
values: arg
},
async: true,
beforeSend: function () {
$("#filter tr").live('click', function () {
document.getElementById('filter_btn').style.pointerEvents = 'none';
});
$('#filter_loading').fadeIn();
},
success: function (data) {
$('#filter_loading').fadeOut();
$("#filter tr").live('click', function () {
alert("does not shown");
if (isSection == false) {
$('#filter_btn').click().promise().done(function () {
document.getElementById('filter_btn').style.pointerEvents = 'auto';
});
}
});
}
});
The alert is not shown, but if I write out side of the AJAX directly like:
$("#filter tr").click(function () {
alert("clicked " + isSection);
Then it will show. Any suggestions please? I can make a function that will be called in success but I don't know about what to do in beforeSend()
Try this one , live method is depreciated long ago. Instead of live you can use the $.on() , $.bind() or something like that..
$.ajax({
type: "POST",
url: 'file url',
dataType: "json",
method : "post",
data: { values: arg },
async: true,
beforeSend: function(){
$("#filter tr").on('click', function () {
document.getElementById('filter_btn').style.pointerEvents = 'none';
});
$('#filter_loading').fadeIn();
},
success: function (data) {
$('#filter_loading').fadeOut();
$("#filter tr").click(function () {
alert("does not shown");
if (isSection == false) {
$('#filter_btn').click().promise().done(function () {
document.getElementById('filter_btn').style.pointerEvents = 'auto';
}
});
}
});
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;
}
}
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;
}
}