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
Related
I have a div element in my index.cshtml with id #myresults and i am trying to load data through jquery.load method by calling a mvc controller method. But i am not able to get the right syntax.
I am passing a custom object as a parameter as well.
var mycustomObject = {
obj1:value1,
obj2:value2,
..
}
The following does not work...(an i have tried other combinations as well..i get server not found error)
$("#myresults").load ('#Url.Action("MyActionMethod","Home")',mycustomObject);
while the following works
$("#myresults").load('/Home/MyActionMethod', mycustomObject);
While the last statement works, it works only on localhost.
Whats the right syntax to use for jquery load with Url.Action ?
#Url.Action() will always generate the correct url, so if your getting a 404, it means this code is in an external script file. Razor code is not executed in external scripts so your url would literally be the text "#Url.Action("MyActionMethod","Home")".
Options to solve this include
moving the code into the view or its layout
declaring a global variable in the view - var url =
'#Url.Action("MyActionMethod","Home")'; an in the external file use
$("#myresults").load(url, mycustomObject);
assign the url to an element as a data-* attribute, for example
<button type="button" id="loadSomething" data-url="#Url.Action("MyActionMethod","Home")">...</button>,and in
the external file
$('#loadSomething').click(function() {
var url = $(this).data('url');
$("#myresults").load(url, mycustomObject);
});
Define the div element as:
<div id="myresults" onload="loadMyData();"></div>
And make the ajax call in your method:
<script type="text/javascript">
function loadMyData() {
$.ajax({
cache: false,
url: '#Html.Raw(Url.Action(MyActionMethod","Home"))',
data: { obj1:value1, obj2:value2 },
dataType: "json",
type: 'post',
success: function (result) {
if (result.success) {
$('#myresults').html(result.data);
}
else {
alert("Failed to load data!");
}
}
});
}
</script>
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()
{
}
I am using jquery tabs and trying to use the onclick function but it seems it is not firing. When user clicks the tab and i want to change the detailview mode into readonly mode. Here is my code in aspx:
<div id="tabs-2" class="column" onclick="ChangeMode">
and here code behind:
protected void ChangeMode()
{
if (DV_Test.CurrentMode == DetailsViewMode.Insert)
{
DV_Test.ChangeMode(DetailsViewMode.ReadOnly);
LoadDet();
}
}
I am using this code that forces the pageto stay the selected tab when post pack occurs and it works fine.
<script type="text/javascript">
var selected_tab = 1;
$(function () {
var tabs = $("#tabs").tabs({
select: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
});
I'm assuming you're using ASP.NET C# because of your tags and syntax. I can suggest these options: use Razor view, or use the JavaScript/jQuery you're already using.
If you prefer to use the Razor View, take a look at the references in this question and use the # symbol to call server functions. In this case, #ChangeMode is what you're looking for.
Since you're using jQuery already I suggest you write a JavaScript function using jQuery .click(). Since the JavaScript and jQuery are both able to call the server, you will be able to access your server-side function ChangeMode.
$('#tabs-2').click(function(){
//Make call to server here. You can use [Ajax][4],
//or see the link below concerning ASP.NET C#
});
link, see this fiddle
Ajax calls:
I've found the jQuery .ajax() call very useful, and this is what my .ajax() calls usually look like:
//get information from server and inject in my div with id="mydiv"
$.ajax({
url: '/ControllerName/MethodName',
type: 'POST',
data: ko.toJSON({myvariable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#mydiv').html('visiblity', 'visible');
},
error: function (error) {
alert('Cannot retrieve data');
}
});
Also, I'm not sure what you've decided on using, but I liked these suggestions for tabs: try the html found here, which uses ul/li and a to make the tabs themselves. The thing that triggers the action is typically the a.
I have JavaScript code that calls a method in ASP.NET. Basically, I have a SqlDataSource connected to a GridView, and I want to change the SelectCommand of the DataSource without causing a postback.
Right now, I am using __dopostback method, but as I said I don't want the page to reload. I just want the GridView to update. Is this possible?
That's not how is done. There are many approaches to this but the easiest is to enclose your content inside an UpdatePanel and drop a ScriptManager on your page.
for example:
<asp:ScriptManager id="mymanager" runat="server" />
<asp:UpdatePanel id="mainPanel" runat="server">
<ContentTemplate>
<! -- Put your content here -->
</ContentTemplate>
</asp:UpdatePanel>
Now all interactions on your page will be done via Ajax.
Better approach (the one I use currently)
Use jQuery to make your Ajax calls in conjunction with a Web Service.
Sample code:
[System.Web.Script.Services.ScriptService]
public class MyWebService: System.Web.Services.WebService
{
[WebMethod]
public List<BusinessObject> GetSomeData(int dataID)
{
//Invoke your business layer and get some data here
List<BusinessObject> result = BusinessLayer.GetSomeData();
return result;
}
}
Using jQuery on the client-side, you can do something like this:
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "MyWebService.svc/GetSomeData",
data: {'dataId': you_id_here },
success: function(result) {
//result.d will contain an array of BusinessObject in JSON format
//You can iterate through this list and populate your html using this data.
//You can either use jQuery templates
//or one of the many jQuery plugins for tabular data.
//I use datatables:
//http://datatables.net/
for(int i=0;i<result.d.length; i++)
{
//do something here if you want to iterate one by one constructing your
//html
}
},
error: function(xhr, ajaxOptions, thrownError) {
//display error here
});
}
});
I highly recommend looking at these links:
http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
http://encosia.com/simplify-calling-asp-net-ajax-services-from-jquery/
Put the GridView into the asp:UpdatePanel. All the postbacks involving the Grid will change to callbacks and your grid should be updated without reloading the whole page.
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"',