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;
});
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")
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.
<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
}
So I'm converting a site form VB to C# and using TypeScript in the process. I have it successfully passing the data to the controller, however the controller post back to the same page instead to the next page.
Here's the TypeScript (full module here)
function formSubmission(submitId, submitUrl, formData, validation) {
if (!submitId || hasSubmit)
return false;
if (validation) {
if (!$("#empApp form").validate().form())
return false;
hasSubmit = true;
}
hasSubmit = true;
// add load status functionality
$(".modal").modal("show");
$.ajax({
type: "POST",
url: submitUrl,
data: formData,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (response) {
window.location.href = "/employment/application/references";
},
error: function (xhr, ajaxOptions, error) {
$(".modal-body").html("<h3>" + status + "<small>" + error + "</small></h3>");
setTimeout(function () {
$(".modal").modal("hide");
}, 100);
window.location.href = "/employment/application/work-experience";
}
});
}
Here's the Controller (full here)
[HttpPost, Route("Work-Experience")]
public ActionResult WorkExperience(List<EmploymentApplicationWorkExperience> appExperience)
{
EmploymentApplication empAppSession = getApplication();
if (!HasSession()) { return InvalidAppSession(); };
SetupViewBag();
if (!empAppSession.Steps.HasFlag(EmploymentApplication.ApplicationStepTypes.EducationSkills))
{
return PartialView(GetApplicationStepError());
}
if (ModelState.IsValid)
{
if (appExperience != null)
{
empAppSession.ApplicationWorkEperiences = appExperience;
// empAppSession.Application.empApWorkExperiences = (ICollection<empApWorkExperience>)appExperience;
empAppSession.StepCompleted(EmploymentApplication.ApplicationStepTypes.Workexperiences);
updateApplicationStep(empAppSession.Steps);
updateApplicationWorkExpriences(empAppSession.ApplicationWorkEperiences);
updateApplication(empAppSession.Application);
return RedirectToAction("References");
}
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
else
{
return PartialView(GetApplicationView("WorkExperience"), empAppSession.ApplicationWorkEperiences);
}
}
Used a unnecessary filter on Controller that if not valid, would continue to return the current page. Once removed, page continued with out post back issue.
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;
}
}