how to raise a C# event or function in javascript - javascript

I have a function in my login page an it access is protect like other C# function by default.
protected void MyFunction()
{
//do somthing
}
I want to raise it in JavaScript something like this
<script>
$.rise(MyFunction)
</script>
Someone said should use
__doPostBack(control, arg);
Or
<a .... onclick="TriggerPostBack('control', 'arg')" .. />
Or....
but all of this is for an ASP.NET object and if you use ASP.NET object it automatically generate callback and __doPostBack and everything you need.
Unfortunately I dont have an ASP.NET object and I use a simple HTML tag and want to raise a c# function by JavaScript manually.
is it possible? and the access of function what should be? and about the security? is it logical or illogical?
At the end I want to postback happen because I am familiar with jQuery AJAX and in this case I dont need it. I want postback happen.

Change your method to a static webmethod and try an jquery ajax post.
$.ajax({
type: "POST",
url: "YourPage.aspx/MyFunction",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
alert(response.d);
}
});
[WebMethod]
public static void MyFunction()
{
}

Related

Jquery Autocomplete with ASP.NET Issue

I am using JqueryUI autocomplete widget with asp.net
i create one class file that contain method that will return list of search result.
and on aspx page i called all required jquery file.
on Script part i write below code:
<script type="text/javascript">
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CommonOperation.cs/GetClientName",
data: "{'SearchVal':'" + document.getElementById('<%=txtSearch.ClientID%>').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error......");
}
});
}
});
});
</script>
don't know what problem is their but when i run it always goes in Error part.
You can't put your web method in a class file, as the method itself needs to be web-accessible.
Move it to a standard ASPX page's code-behind, and use the .aspx link instead of .cs.
An alternative would simply be to use an .asmx, and attach your class to that instead. This answer provides some information on that:
You could use something like an asmx (ASP.Net web service) that exposes the webmethods. The file is basically just a markup place holder that points at a class file. Contents are just:
<%# WebService Language="C#" CodeBehind="~/foo/MyClass.cs" Class="MyClass" %>
Then your class has to inherit from System.Web.Services.WebService and you should be good.
If you do an add file from Visual Studio and add a web service file you can get it to create all this for you.
here url should be like this-> url:"CommonOperation.aspx/GetClientName",
Done It
Method will be static and declared as WebMethod and Call it from aspx.cs

Call WebMethod in C# codebehind without using a server form in ASPX page

Due to issues with styling, and needing multiple forms on one single web page, I currently have a form that is outside of the normal form with runat=server.
Is it possible for me to still call a WebMethod in the C# codebehind of this web page using ajax? I want to submit the information from this form to the same connection string that I am using earlier in the page, in a different form.
Here is my current code:
$().ready(function () {
$("input[type=submit]").click(function () {
handleClick();
createJob();
});
});
function createJob() {
var txtTestValue = document.getElementById('jobTitle').value;
$.ajax({
// POST signals a data request
type: "POST",
// This directs which function in the c# code behind to use
url: "Account/help.aspx/CreateJob",
// The paramater pageIndex, page number we need to load, to pass to GetCustomers(int pageIndex)
data: txtTestValue,
// Type of data we are sending to the server (i.e. the pageIndex paramater)
contentType: "application/json; charset=utf-8",
// Type of data we expect back from the server (to fill into the html ultimately)
dataType: "text",
// If all goes smoothly to here, run the function that fills our html table
success: OnSuccess,
// On failure, error alert user (aka me so that I know something isn't working)
failure: function (response) {
alert("failure");
},
error: function (response) {
alert("error");
}
});
});
And my WebMethod in the codebehind:
[WebMethod]
public string CreateJob()
{
//rest of my database code here
}
Sorry for the confusion but it's doing everything right up until the ajax code, and then seems to ignore it (and returns that the ajax failed with an error). My code is not reaching the WebMethod and any breakpoints I set in Visual Studio are not triggered in the page header. Thanks in advance for your help!
You need to declare the method as static.
[WebMethod]
public static string CreateJob()
^^^^^
{
//rest of my database code here
}
Another issue is if input[type=submit] is ASP.Net Button control, it will post back to server. You cannot use ASP.Net Server control to make jQuery Ajax call - $.ajax.
// This code won't work if `input[type=submit]` is a server button control
$(function () {
$("input[type=submit]").click(function () {
handleClick();
createJob();
});
});
you need to use regular html input or button control with type=button instead of type=submit.
The webmethod should be static.
[WebMethod]
public static string CreateJob()
{
//rest of my database code here
}

Access ASP control from static method

I can't achieve this one:
I have a dynamically-generated table in HTML. One of the columns contains just links, it's a column that contains tags. So every link has assigned a function that makes an ajax call and communicates with an aspx:
function cargaDatosModificacion(id) {
var dto = {};
dto.idPromoBanco = id;
var dtoJSON = JSON.stringify(dto);
$.ajax({
async: false,
url: 'PromosBancos.aspx/CargaDatosModificacion',
cache: false,
dataType: 'json',
type: "POST",
data: dtoJSON,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
},
error: errorResponse
});
}
So as you can see, the function receives an ID an calls 'PromosBancos.aspx/CargarDatosModificacion' via ajax.
Well, that aspx contains some ASP controls, like textbox and stuff.
When I try to 'do the stuff' with that controls, I notice that I don't have access to them. So yes, it's the 'static' clause.
Obviously when I get rid of the 'static' keyword, I won't be able to make the ajax call work.
I tried making every control static, didn't work either.
So I'm in the middle of this trouble, and the question is: Is there ANY chance that I can access to the ASP Controls from a static method?
Or: Is there any way to achieve what I'm trying to do? (access ASP controls after clicking on a HTML element).

Executing dynamic javascript from an ajax call

I have a web application that is powered by ASP.NET on the server side and Javascript/jQuery on the client side. I'd like to know if it's possible to make an Ajax call to an ASP.NET WebMethod and have the returned javascript code executed. For example (very simplified example):
My HTML:
<html>
<head>
<title></title>
</head>
<body>
<div id="divMessage"></div>
</body>
</html>
In my C#:
[WebMethod]
public static string GetScriptCode()
{
return "$('#divMessage').html('This is a test');";
}
In my javascript:
$(function() {
var handler = function(msg) {
var myScriptCode = msg.d;
// I'd like $('#divMessage') to contain my message
};
$.ajax({
type: "POST",
url: "Test.aspx/GetScriptCode",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: handler
});
});
I'd like the javascript that is returned from my GetScriptCode() to execute. Any ideas how to do this?
using eval() is one option, but as everyone say eval is evil, don't use it.
I normally do it using a dynamic function like so:
var theCode = "$('#divMessage').html('This is a test');";
var F=new function (theCode);
return(F());
Sort of looks like reinventing the eval, but that's how I do it as of now.

Passing data from ASP.NET View to a Controller Async using JS in .NET core

I want to preface that I know this question has been asked before, but I haven't found a concrete answer that works on .NET core.
I am trying to pass a Model Value back to my controller so I can do some work on it. Can I use Razor URL helpers to send the URL as #Url.Action("Action", "Controller") within the .ajax URL? Also, how can I send data to do work on async? Here is my script file:
$('#ajaxBtn').on('click', function (e) {
$.ajax({
url: "/Home/AjaxReturn",
type: "POST",
dataType: "json",
data: 'data: 12345',
success: function () {
}
});
});
Here is my Controller code:
[HttpPost]
public void AjaxReturn(JsonResult data)
{
var thisData = data;
}
** I am using this for a responsive js datatable (datatables.net) eg. on a DELETE click I want to pass the ID back to the controller so I can delete the record and then pass back a status.
try to change the parameter in your ajax code.
data: '"data": "12345"',

Categories

Resources