Calling a C# method from .js file - javascript

I have a aspx page and in that i have method UpdateScreenAlertStatus();
I want to have a file called dtml.js and in that i have function openmodelpopup().
I want to call UpdateScreenAlertStatus(); in javscript method openmodelpopup().

function MyMethod() {
$.ajax({
type: "POST",
url: "abc.aspx/UpdateScreenAlertStatus ",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
Call the above ajax in your js function openmodelpopup().
[WebMethod]
public static void UpdateScreenAlertStatus()
{....}

Make it a web method
[WebMethod]
public static string UpdateScreenAlertStatus()
{....}
Refer this MSDN article.
From javascript you can access this as YourPage.aspx/UpdateScreenAlertStatus or through PageMethods in same aspx page. You can call this with the following javascript.
function openmodelpopup() {
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "YourPage.aspx/UpdateScreenAlertStatus",
success: (function (data) {
$("#statusDiv").text(data.d);
$("#statusDiv").show();
}),
error: (function () {
alert("Error occurred in server!");
})
});
}
I'm assuming here, 1. your C# method is static and marked WebMethod. 2. Code is compiled properly. 3. You are using jQuery. 4. The url in javascript is correct. 5. Your C# method returns a string status. 6. You are trying to update html element statusDiv with that string.

Related

Cannot send data from aspx file to code behind using $.ajax({ type: "POST", using VS2017 C#

I'm using web-forms to collect data from a form and then send the data to the code-behind to send to an API. Using a button I'm calling a JavaScript method which collates the data and then sends to my aspx.cs file to send to the API. The Html code for the button is
<button class="search btn" ID="btnSearch" onclick="searchApi(); return false;"><i class="fas fa-search"></i>Search</button>
This runs the searchAPI() function which works and creates a concatenated string called SearchData. The Javascript code looks like this
var searchString = JsonData;
var trimsearchString = searchString.replace(/,/g, '');
$.ajax({
type: "POST",
url: 'Default.aspx/GetApi',
data: searchString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (errordata) {
console.log(errordata);
alert(errordata);
}
});
The method GetAPI in my Default.aspx.cs file is never called. The method code is
[System.Web.Services.WebMethod]
public static void GetApi(string searchData)
{...
The success: function (data) returns success but the code behind method is never called, can someone please tell me what I am missing.
fix the ajax data, it seems that method with this parameter can' t be found
$.ajax({
type: "POST",
url: 'Default.aspx/GetApi',
data: { searchData: trimsearchString},
//or if it is still problem, you can even try
data: JSON.stringify( { searchData: trimsearchString}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
},
error: function (errordata) {
console.log(errordata);
alert(errordata);
}
});
and your webmethod should return something
[WebMethod]
public static string GetApi(string searchData)
{
return searchData
}

how to pass java script values to controller using post method in .net core application?

I am developing .net core application.i need to pass java script values to my controller using Post method. i am using java script code is below
data = {'imageValue':'some test'}
$.ajax({
type: 'Post',
url: '/Home/UploadData',
dataType: 'json',
contentType: 'application/json',
data: data,
success: function (data) {
alert(data);
console.log('sample');
},
error: function(){
}
});
my controller is
[HttpPost]public string UploadData([FromBody] string imageValue)
{return imageValue;} but imageValue always it return null.if any mistake in my code please solve the problem.
When you make the ajax call, you should stringify the javascript object and send it. You can use the JSON.stringify method to convert the js object to it's JSON string equivalent.
var data = {'imageValue':'some test'}
$.ajax({
type: 'Post',
url: '/Home/UploadData',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (data) {
console.log('sample', data);
},
error: function(){
}
});
Now since the ajax call is sending the data in the request body (since it is a POST request),You need to decorate the HttpPost action method parameter with [FromBody] attribute so that model binder knows it should read the data from the request body and map to the method parameter(YourViewModel) object.
public IActionResult UploadData([FromBody] YourViewModel d)
{
return Json(d);
}

How to use a var in ajax url with action razor syntax

I have a function that calls a method in controller through an Action URL, but I need use a parameter like name of Method, but this is not possible in this way.
function changeDropDownList(id, dropNameToChange, actionName, descriptionName) {
var control = $('#'+dropNameToChange);
control.prop("disabled", false);
$.ajax({
//Here I need use the actionName var, but only accept a string
url: '#Url.Action(actionName, "ThirdPartiesDef")',
dataType: "JSON",
data: { id: id },
contentType: "application/json; charset=utf-8",
success: function (result) {
control.empty();
$.each(result, function (index, item) {
control.append(
$('<option/>', {
value: item.Id,
text: item[descriptionName]
})
);
});
},
error: function (error) {
alert("Error: " + error);
}
});
}
I don't know so much of ajax and if you can say me some more easy method, it's ok.
Thank you for your help
You could use a placeholder inside the Url.Action server side Razor function that will be replaced by your javascript actionName variable on the client side:
url: '#Url.Action("#THE-ACTION#", "ThirdPartiesDef")'.replace('#THE-ACTION#', actionName)
which basically will emit the following markup inside the browser on the client:
url: '/#THE-ACTION#/ThirdPartiesDef/'.replace('#THE-ACTION#', actionName)
which after calling the changeDropDownList javascript function on the client it will replace the placeholder with the actionName javascript variable and you will end up with the correct url to use for your AJAX call.
As a side note you should remove the contentType: "application/json; charset=utf-8" parameter from your AJAX call because you are not sending any JSON at all in your data parameter.
You have to use JSON.stringify() method.
JSON.stringify() method turns a javascript object to json text and stores it in a string.
You specified contentType: "application/json; charset=utf-8", and the server waits to receive data in json format.
Also, you used wrong #Url.Action : #Url.Action(actionName, "ThirdPartiesDef")',.
One solution is to use .replace function:
'#Url.Action("myAction", "ThirdPartiesDef")'.replace('myAction', actionName).
In Razor every content using a # block is automatically HTML encoded by Razor.

Jquery ajax not calling server side function

I have solution structure as:
I want to call recommendationProcess function from CTL_RateRecommendationDetails.ascx.cs from
CTL_RateRecommendationDetails.ascx
So i written code as:
$.ajax({
type: "POST",
url: "/UserControls/CTL_RateRecommendationDetails.ascx/recommendationProcess",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(value) {
alert(value.d);
},
error: function(e) {
alert("Ajax Error" + JSON.stringify(e));
}
});
But every time it comes in error block.
I have tried with :
url: "/CTL_RateRecommendationDetails.ascx/recommendationProcess",
And
url: "CTL_RateRecommendationDetails.ascx/recommendationProcess",
But its not calling function.
[System.Web.Services.WebMethod]
public static void recommendationProcess()
{
}
You can't call code behinds of user controls from JQuery Ajax
Ref : http://forums.asp.net/t/1423555.aspx
Using jQuery AJAX to call ASP.NET function in control code-behind instead of page code-behind
how-to-access-server-side-method-in-ascx-control-using-jquery-ajax-method

ajax client-to-server side

part a) I m trying to send the value stored in the variable 'mem_ID' from my javascript page...default.aspx to my server side - default.aspx.cs page. But I keep getting an error message.
$.ajax({
type: "POST",
url: "default.aspx.cs",
data: "{mem_ID : ' " + mem_ID + "'}",
async: true,
// success: function (result) { }
});
$ - is undefined.
Expected identifier or string.
part b) Also once i send this to the server side, how do i receive the value stored in the mem_ID ??
You could use a PageMethod. Let's take an example of such a method in your code behind:
[WebMethod]
public static string MyMethod(string memId)
{
return string.Format("Thanks for calling me with id: " + memId);
}
Things to note: the method must be static and decorated with the [WebMethod] attribute.
And on the client side you could invoke this method using the jQuery.ajax() function like this:
$.ajax({
url: 'default.aspx/MyMethod',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ memID : mem_ID }),
success: function (result) {
alert(result.d);
}
});
Also the error you are getting about the undefined $ symbol is related to the fact that you didn't reference the jQuery library in your page. So make sure that in your WebForm you have actually added reference to the jQuery library before using it. For example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" type="text/javascript"></script>

Categories