How to call jquery ajax to c# page there is no response from visual studio tried through break point
first tried with Big one no response from C# side(ProfitCentersNameInsert) function then tried another simple type (apply) function but no response from both methods
just commented the below lines on Ajax
// url: "ProfitCentersScreen.aspx/ProfitCentersNameInsert",
// data: "{'ProfitCenterName':'" + ProfitCenterName + "'}",
JS Code
$(function() {
profit.onRefresh()
$( "#btnAdd" ).click(profit.onClickSave);
});
var profit = {
onRefresh: function(){},
onClickSave: function(){
var ProfitCenterName =$('#txtProfitCenter').val();
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
// url: "ProfitCentersScreen.aspx/ProfitCentersNameInsert",
url: "ProfitCentersScreen.aspx/apply",
// data: "{'ProfitCenterName':'" + ProfitCenterName + "'}",
data:'{}',
async: false,
success: function (response) {
alert( response );
alert(ProfitCenterName);
$('#txtProfitCenter').val('');
alert("Record saved successfully..!!");
},
error: function () {
alert("Error");
}
});
}
};
C# Code
[WebMethod]
public static string ProfitCentersNameInsert(string ProfitCenterName)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=192.168.0.133;User Id=hll; " + "Password=hll;Database=checking_DB;"); //+ "Pooling=true;MaxPoolSize=100;Timeout=20;"
try
{
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("Insert into tbl_Profit_Centers(Profit_Center_Id,Profit_center_Name) Values(default,#ProfitCenterName)", conn);
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("#ProfitCenterName", ProfitCenterName);
command.ExecuteNonQuery();
conn.Close();
return "Success";
}
catch (Exception ex)
{
return "failure";
}
}
[WebMethod]
public static string apply()//method must be "pulic static" if it is in aspx page
{
return "Hi";
}
try This
url: "ProfitCentersScreen.aspx",
data: {ProfitCenterName: ProfitCenterName}
Try below points, it should work :
1) if your page is at root level of project then the url should be like below :
url: "/ProfitCentersScreen.aspx/apply"
OR
url: "../ProfitCentersScreen.aspx/apply"
2) stringify your parameter
data: JSON.stringify({})
3) Finally add this parameter
dataType: "json",
Try using response.d in your success
success: function (response) {
alert(response.d);
alert("Record saved successfully..!!");
},
Here's pseudo code a simple jQuery Ajax call
jQuery:
$("#bntAJax").on('click', function (e) {
$.ajax({
type: "POST",
// your webmethod
url: "AjaxFunction/myFunction.asmx/apply",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json", // dataType is json format
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
alert(response.d);
}
function OnErrorCall() {
}
e.preventDefault();
});
WebMethod :
[WebMethod]
public string apply()
{
return "Hello";
}
Related
I am writing CRUD application using ASP.NET MVC, KnockoutJS and database. When I write separate viewmodel for Create, Read, Update and Delete. and calling each view model in separate view (Create, Read, Update and Delete) then It's working fine. But when I include all view model in one single view model, then calling that view model in every View. Then I am neither able to create nor able to edit.
Please help me with this. I tried so many ways but could not get a proper solution.
I have written this function using Knockout:
$(function() {
ko.applyBindings(modelView);
});
Var parsedSelectedCourse = $.parseJSON(selectedCourse);
var modelView = {
Read: {
Courses: ko.observableArray([]),
viewCourses: function() {
var thisObj = this;
try {
$.ajax({
url: '/Home/ListCourses',
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function(data) {
thisObj.Courses(data); //Here we are assigning values to KO Observable array
},
error: function(err) {
alert(err.status + " : " + err.statusText);
}
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Create: {
CourseName: ko.observable(),
CourseDescription: ko.observable(),
createCourse: function() {
try {
$.ajax({
url: '/Home/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this), //Here the data wil be converted to JSON
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Update: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
updateCourse: function() {
try {
$.ajax({
url: '/Home/Update',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Delete: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
deleteCourse: function() {
try {
$.ajax({
url: '/Home/Delete',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
}
};
function successCallback(data) {
window.location.href = '/Home/Read/';
}
function errorCallback(err) {
window.location.href = '/Home/Read/';
}
Java Script:-
function themechange(themeValue) {
$('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
In LoginContoller.cs:-
[HttpGet]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}
All the suggestion which replied so far are not working. Please give a executable project codes links for ASP.NET MVC Application which applies simple ajax with json for just calling a controller method.
You forget to assign the themeValue which get from HTML page by $('#themeId') also there is a problem you use GET instead of POST.
Try this
function themechange(themeValue) {
var themeValue = $('#themeId').attr('href', '/zcv/resources/css' + '/' + 'theme-' + themeValue.toLowerCase() + '.css');
$.ajax({
url: '#Url.Action("ChangeTheme", "Login")',
type: 'POST',
dataType: 'json',
cache: false,
data: { 'themeValue': themeValue },
success: function (data) {
alert(data);
},
error: function () {
alert('Error occured');
}
});
}
[HttpPost]
public JsonResult ChangeTheme(string themeValue)
{
System.Diagnostics.Debug.WriteLine("======ChangeTheme======");
Session["theme"] = themeValue;
String x= "========";
return Json(x, JsonRequestBehavior.AllowGet);
}
I have a website www.arabadukkan.com
I have cascading comboboxes at the top (araç türü->marka->model etc)
I am calling a webmethod to return the results but the result is the html of entire page.
This code works great in my local
WebMethod code :
public static string GetMarkas(string selectedId)
{
var items = Service.DS.GetMarkas().WithCategoryId(selectedId.SayiVer());
string donen = "<option value=''>Tüm Markalar...</option>";
foreach (var item in items) donen += string.Format("<option value='{0}'>{1}</option>", item.id, item.Title);
return donen;
}
I couldnt find any solution. When i look the network tab in chrome i see the GetMarkas response header is "Content-Type:text/html; charset=utf-8"
My script is :
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: $.toJSON(veriler),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
Try below code I guess u don't require json here..
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: { selectedId : veriler},
dataType: 'html',
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
You may want to make sure that you've added necessary web.config entries, specifically httpModules section. Please go through this
why JSON doesn't work with html text (var text_html = '<p></p><t></t>'; ) but this will be work correct (var text_html = 'example';)
doesn't work
var text_html = JSON.parse('<p></p><t></t>');
Problem:
function Save() {
var text_html = '<p></p><t></t>';
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
My_Text: text_html
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
public JsonResult DodajTematSave(string My_Text)
{
return Json(new { Success = true});
}
also this doesn`t work
var dom_string = '<div>xxx<div>yyy</div></div>';
var text_html = dom_string.innerText();
also this doesn`t work
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
try this:
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
and use ajaxSetup to instruct JQuery how to handle the data type
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Because those are escaping characters in JSON. You will have to parse html in a way to make it JSON friendly if you wanted it passed through JSON.
For this people who have problem with this I can show another way to fix this problem but very ugly click here
I want to read data which is posted in JSON in my c#.net application? I am very new with this JSON and POST method?
Can anyone please help me?
I am posting data from page1. to other page2 (smsstaus.aspx in my case) for testing purspoe.
I want to read that JSON posted data in PageLoad of Page2.
Sample code.....
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
You could define a WebMethod in your smsstatus.aspx (SendStatus for example)
An implementation could look something like this (from the top of my head)
[WebMethod]
public static void SendStatus(string sid, string status)
{
// retrieve status
}
Now you can create a request to consume this method, like this:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx/SendStatus",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
.NET wil deserialize the json string to and pass them as arguments to SendStatus
when you are using Jquery and you throw JSON in the data thingy it will change in a normal Post but what you are now doing is gonna give problems change the code to:
function SendSMSStatus() {
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: {"SmsSid":$("#<%= txtSmsSid.ClientID%>").val(),"SmsStaus": $("#<%= txtSmsStaus.ClientID%>").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert('update the db here');
},
error: function () { }
});
}
and you can use the normal POST but if you want to play with JSON in C# see this aritcle
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
Do not change the contentType if you want to request the aspx (WebForm) and not the WebMethod. (When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded").
$.ajax({
type: "POST",
url: "myurl/smsstatus.aspx",
data: '{"SmsSid":"' + $("#<%= txtSmsSid.ClientID%>").val() + '","SmsStaus":"' + $("#<%= txtSmsStaus.ClientID%>").val() + '"}',
dataType: "json", // The type of data that you're expecting back from the server.
success: function (msg) {
alert(msg.d);
},
error: function () { }
});
Receive data from the Page_Load handler,
//Read Form data
string testData = Request["SmsSid"] + " " + Request["SmsStaus"];
//Prepare Json string - output
Response.Clear();
Response.ContentType = "application/json";
Response.Write("{ \"d\": \"" + testData +"\" }");
Response.Flush();
Response.End();