I have DataTable with external button (search) to filter data, It works fine with first time load / page load (refer 1st time click.PNG)
I need to filter table with multiple criteria so added a search button on the same page and called reload function
I search click it re-loads data correctly but grid click event doesn't work after search button click
how to resolve this?
1st time grid click works
ASP.NET page
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<style type="text/css">
</style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:UpdatePanel ID="UpdatePanelSalesOrder" runat="server">
<ContentTemplate>
<div class="row no-gutters">
<div class="col-sm-3">
<select class="custom-select custom-select-sm" runat="server" id="txtCategory">
</select>
</div>
<div class="col-sm-3">
<asp:Button ID="btnSearch" runat="server" Text="Search" CausesValidation="False"
CssClass="btn btn-secondary btn-sm btn-block" OnClick="btnSearch_Click" />
</div>
<div class="col-sm-6">
</div>
</div>
<table id="tblOrder" class="table-striped table-bordered table-hover table-sm" style="width: 100%">
<thead>
<tr style="height: 35px">
<th>Ord.No</th>
<th>Date</th>
<th>Product Name</th>
</tr>
</thead>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="theScript" runat="server">
<script type="text/javascript">
$(document).ready(function () {
fill_table();
$('table tbody').on('click', 'tr', function () {
alert("Data Table clicked");
});
});
function fill_table()
{
var table = $('#tblOrder').DataTable(
{
'bPaginate': true,
'bLengthChange': false,
'bFilter': false,
'bInfo': true,
'bAutoWidth': false,
'responsive': false,
"scrollX": true,
'ajax': {
url: "SalesOrderIssue.aspx/get_PendingOrder",
method: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
dataSrc: function (data) {
return $.parseJSON(data.d)
}
},
'columns': [
{ data: "ORDER_NO" },
{ data: "ORDER_DATE", type: "date", render: function (data) { return moment(data).format("MM/DD/YYYY"); } },
{ data: "ProductMaster.PRODUCT_NAME" },
{ data: "SizeMaster.SIZE_NAME" },
],
'order': [[1, 'asc']],
'error': function (xhr, status, error) {
alert('Error Occured -' + error);
}
})
}
function reload_data() {
fill_table();
}
</script>
</asp:Content>
Code behind
[WebMethod]
public static string get_PendingOrder()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string strOrderList = serializer.Serialize(_listOrderMasterDTO);
return strOrderList;
}
private void fill_PendingOrder()
{
try
{
var ActiveDate = DateTime.Now;
var startOfMonth = new DateTime(ActiveDate.Year, ActiveDate.Month, 1);
DateTime dtFromDate = Functions.ConvertToDateTime(m_strStartDate);
DateTime dtToDate = Functions.ConvertToDateTime(m_strEndDate);
_listOrderMasterDTO = new OrderMasterService().GetOrderMasterByDateAndSubCatIdList(dtFromDate, dtToDate, "", 0, Convert.ToString(txtCategory.Items[txtCategory.SelectedIndex].Text), Convert.ToString(Session["g_DBNAME"]));
}
catch (Exception ex)
{
Module.ShowError(ex, this, this.Page.GetType());
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
try
{
fill_PendingOrder();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("$(function(){");
sb.Append("reload_data();");
sb.Append("});");
ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "", sb.ToString(), true);
}
catch (Exception ex)
{
Module.ShowError(ex, this, this.Page.GetType());
}
}
Related
I am new to knockout.js and i am using post method to update data into database . Here is my code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SProduct.aspx.cs" Inherits="SProduct" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="body">
<h2>
Knockout CRUD Operations with ASP.Net Form App</h2>
<h3>
List of Products</h3>
<table id="products1">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Category
</th>
<th>
Price
</th>
<th>
Actions
</th>
</tr>
</thead>
<tbody data-bind="foreach: Products">
<tr>
<td data-bind="text: Id">
</td>
<td data-bind="text: Name">
</td>
<td data-bind="text: Category">
</td>
<td data-bind="text: formatCurrency(Price)">
</td>
<td>
<button data-bind="click: $root.edit">
Edit</button>
<button data-bind="click: $root.delete">
Delete</button>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
</td>
<td>
</td>
<td>
Total :
</td>
<td data-bind="text: formatCurrency($root.Total())">
</td>
<td>
</td>
</tr>
</tfoot>
</table>
<br />
<div style="border-top: solid 2px #282828; width: 430px; height: 10px">
</div>
<div data-bind="if: Product">
<div>
<h2>
Update Product</h2>
</div>
<div>
<label for="productId" data-bind="visible: false">
ID</label>
<label data-bind="text: Product().Id, visible: false">
</label>
</div>
<div>
<label for="name">
Name</label>
<input data-bind="value: Product().Name" type="text" title="Name" />
</div>
<div>
<label for="category">
Category</label>
<input data-bind="value: Product().Category" type="text" title="Category" />
</div>
<div>
<label for="price">
Price</label>
<input data-bind="value: Product().Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.update">
Update</button>
<button data-bind="click: $root.cancel">
Cancel</button>
</div>
</div>
<div data-bind="ifnot: Product()">
<div>
<h2>
Add New Product</h2>
</div>
<div>
<label for="name">
Name</label>
<input data-bind="value: $root.Name" type="text" title="Name" />
</div>
<div>
<label for="category">
Category</label>
<input data-bind="value: $root.Category" type="text" title="Category" />
</div>
<div>
<label for="price">
Price</label>
<input data-bind="value: $root.Price" type="text" title="Price" />
</div>
<br />
<div>
<button data-bind="click: $root.create">
Save</button>
<button data-bind="click: $root.reset">
Reset</button>
</div>
</div>
</div>
<script type="text/javascript">
function formatCurrency(value) {
return "$" + value.toFixed(2);
}
function ProductViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Id = ko.observable("");
self.Name = ko.observable("");
self.Price = ko.observable("");
self.Category = ko.observable("");
var Product = {
Id: self.Id,
Name: self.Name,
Price: self.Price,
Category: self.Category
};
self.Product = ko.observable();
self.Products = ko.observableArray(); // Contains the list of products
// Initialize the view-model
$.ajax({
url: 'SProduct.aspx/GetAllProducts',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
// debugger;
$.each(data.d, function (index, prd) {
self.Products.push(prd);
})
//Put the response in ObservableArray
}
});
// Calculate Total of Price After Initialization
self.Total = ko.computed(function () {
var sum = 0;
var arr = self.Products();
for (var i = 0; i < arr.length; i++) {
sum += arr[i].Price;
}
return sum;
});
//Add New Item
self.create = function () {
Product.Id="333";
if (Product.Name() != "" && Product.Price() != "" && Product.Category() != "") {
$.ajax({
url: 'SProduct.aspx/Add',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:"{item:" + ko.toJSON(Product) + "}",
success: function (data) {
self.Products.push(data.d);
self.Name("");
self.Price("");
self.Category("");
},
error:function(data)
{
alert("error");
console.log(data.d);
}
});
}
else {
alert('Please Enter All the Values !!');
}
}
//Delete product details
self.delete = function (Product) {
if (confirm('Are you sure to Delete "' + Product.Name + '" product ??')) {
var id = Product.Id;
$.ajax({
url: 'SProduct.aspx/Delete',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:"{id:" + ko.toJSON(id) + "}",
success: function (data) {
self.Products.remove(Product);
},
error:function(data){
console.log(data.d);
alert('Error');
}
})
}
}
// Edit product details
self.edit = function (Product) {
self.Product(Product);
}
// Update product details
self.update = function () {
var Product = self.Product();
$.ajax({
url: 'SProduct.aspx/Update',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:"{Product:" + ko.toJSON(Product) + "}",
success: function (data) {
alert("success");
console.log(data.d);
// self.Products.removeAll();
// self.Products(data.d); //Put the response in ObservableArray
self.Product(null);
alert("Record Updated Successfully");
},
error: function (data) {
console.log(data);
}
})
}
// Reset product details
self.reset = function () {
self.Name("");
self.Price("");
self.Category("");
}
// Cancel product details
self.cancel = function () {
self.Product(null);
}
}
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);
</script>
</form>
</body>
</html>
Updated
Here is screen shot of my page . when i click on update ajax success function is called, but no change in above table field .
Why do you have to update the item back to the list? You're not doing anything to the properties of the object on the server side are you?
Your edit method should look something like this:
self.edit = function(item) {
self.Product(item);
};
and remove the following code nemesv said.
self.Products.removeAll();
self.Products(data.d); //Put the response in ObservableArray
My first post so be gentle ;)
Response to comment:
change your success to:
success: function (data) {
var product = ko.utils.arrayFirst(self.Products(), function(item) {
return (item.Id == data.d.Id);
}); // You could either update the product object with the new values from data.d or delete it and add a new product object.
for (var p in product ) {
product [p] = data.d[p];
}
self.Product(null);
alert("Record Updated Successfully");
},
Found a bug, it was replacing the observables with native values.
for (var p in product ) {
product [p](data.d[p]);
}
I took the liberty of simplifying the code and removing everything that hasn't anything to do with the update function. The following code example should work. ( I used knockout 2.3.0 and jQuery 1.9.1)
<script type="text/javascript">
function Product(id, name, price, category) {
var self = this;
self.Id = ko.observable(id);
self.Name = ko.observable(name);
self.Price = ko.observable(price);
self.Category = ko.observable(category);
}
function ProductViewModel() {
var self = this;
self.Product = ko.observable();
self.Products = ko.observableArray(); // Contains the list of products
$.ajax({
url: 'SProduct.aspx/GetAllProducts',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: {},
success: function (data) {
$.each(data.d, function (index, prd) {
var p = new Product(prd.Id, prd.Name, prd.Price, prd.Category);
self.Products.push(p);
});
}
});
self.Total = ko.computed(function () {
var sum = 0;
var arr = self.Products();
for (var i = 0; i < arr.length; i++) {
sum += arr[i].Price;
}
return sum;
});
self.edit = function(product) {
self.Product(product);
};
self.update = function() {
var product = self.Product();
$.ajax({
url: 'SProduct.aspx/Update',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{product:" + ko.toJSON(product) + "}",
success: function (data) {
for (var p in product) {
product[p](data.d[p]);
}
self.Product(null);
alert("Record Updated Successfully");
},
error: function(data) {
console.log(data);
}
});
};
self.reset = function() {
self.Name("");
self.Price("");
self.Category("");
};
self.cancel = function() {
self.Product(null);
};
}
$(document).ready(function() {
var viewModel = new ProductViewModel();
ko.applyBindings(viewModel);
});
</script>
I had earlier asked this question here which worked in a html file. Now I am trying to put the same in the ASP.NET webform but does not seem to work.
What happens here the first time the page loads ajax call fires which I do not want except when the cursor is moved away from the text box
On Blur I have a popup window that I want to show the data returned from the ajax call. The data does not bind either. What am I doing wrong here.
My Javascript:
<script type="text/javascript">
var self = this;
function showPopUp() {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
var SName = document.getElementById("<%=txtSurname.ClientID%>").value
document.getElementById("txtSurnameSearch").value = SName
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100;"
}
this.SurnameViewModel(SName) //<= here I pass the surname to the ViewModel
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
function SurnameViewModel(Surname) {
var self = this;
self.Surnames = ko.observableArray();
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/ChurchID",
dataType: 'json',
data: { "Name":Surname, "ChurchID": "17" },
processdata: true,
success: function (result) {
alert(result.data);
ko.mapping.fromJSON(result.data, {}, self.Surnames);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
$(document).ready(function () {
ko.applyBindings(new SurnameViewModel());
});
</script>
My HTML
<!-- Grey Background -->
<div id="cover"></div>
<!-- Surname Popup -->
<div id="dialog" style="display:none">
My Dialog Content
<br /><input ID="txtSurnameSearch" type="text" />
<br /><input type="button" value="Submit" />
<br />[Close]
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre> //<= just shows the header
<table>
<thead>
<tr>
<th>ID</th>
<th>Family Name</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: Surnames">
<tr>
<td data-bind="value: id"></td>
<td data-bind="value: homename"></td>
</tr>
</tbody>
</table>
</div>
TextBox where the onBlur is called:
<asp:TextBox ID="txtSurname" MaxLength="50" runat="server" Width="127px" class="txtboxes" placeholder="Last Name" onblur="showPopUp();" />
JSON Data returned by the ajax call
{"data":"[{\"id\":3,\"homename\":\"D\\u0027Costa\"}]"}
Edit 1:
If I hard code the values in the ajax call it seems to bind but still fires on page load
data: { "Name":"d", "ChurchID": "17" },
In your view model your Ajax call is inline, not inside a method, so as an instance of its contstructed your AJAX gets fired off. See this code, we create a global variable to hold the instance of your model and then wrap the AJAX call into its on function (method) in your JS. Then you can just call the method on your instance when you need to in your popup code.
var self = this;
var model = new SurnameViewModel();
function showPopUp() {
var cvr = document.getElementById("cover")
var dlg = document.getElementById("dialog")
var SName = document.getElementById("<%=txtSurname.ClientID%>").value
document.getElementById("txtSurnameSearch").value = SName
cvr.style.display = "block"
dlg.style.display = "block"
if (document.body.style.overflow = "hidden") {
cvr.style.width = "1024"
cvr.style.height = "100;"
}
model.GetSurname(SName) //<= here I pass the surname to the ViewModel
}
function closePopUp(el) {
var cvr = document.getElementById("cover")
var dlg = document.getElementById(el)
cvr.style.display = "none"
dlg.style.display = "none"
document.body.style.overflowY = "scroll"
}
function SurnameViewModel() {
var self = this;
self.Surnames = ko.observableArray();
self.GetSurname = function(Surname){
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost/GetSurnames/Name/ChurchID",
dataType: 'json',
data: { "Name":Surname, "ChurchID": "17" },
processdata: true,
success: function (result) {
alert(result.data);
ko.mapping.fromJSON(result.data, {}, self.Surnames);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failure!");
alert(xhr.status);
alert(thrownError);
}
});
}
}
$(document).ready(function () {
ko.applyBindings(model);
});
</script>
I am working on asp.net web page where i am showing you-tube videos using fancy-box.
So far it is working fine, I also need to make an ajax call to asp.net file updateHits.aspx?VideoID=xyzxvtmiw so that i can update the hits/views for this video in the database (when someone clicks the thumbnail). I am not quite sure how to make this call when user click on the image thumbnail of a video on video.aspx page.
Below is part of my script
<script type="text/javascript">
//Code to Reinitialize Fancybox script when using update panel START
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) { }
function EndRequest(sender, args) { InitMyFancyBox(); }
$(document).ready(function () {
InitMyFancyBox();
});
function InitMyFancyBox() {
$(document).ready(function () {
$(".youtube").click(function () {
// first, get the value from the alt attribute
var newTitle = $(this).find("img").attr("alt"); // Get alt from image
$.fancybox({
'padding': 0,
'autoScale': false,
'transitionIn': 'none',
'transitionOut': 'none',
//'title': this.title, // we will replace this line
'title': newTitle, //<--- this will do the trick
'width': 680,
'height': 495,
'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
'type': 'swf',
'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' }
});
return false;
});
});
}
</script>
<asp:Repeater ID="rptvideos" runat="server" >
<ItemTemplate>
<div class="single-video-wrapper">
<asp:HyperLink ID="hylnkvideo" CssClass="youtube" NavigateUrl='<%# getVideoURL(Eval("VideoID"), Eval("VideoYoutubeID")) %>' runat="server">
<div class="video-image-wrapper">
<asp:Image ID="imgvideo" ImageUrl='<%# getVideoImagePath(Eval("VideoYoutubeID"), Eval("VideoYoutubeIcon")) %>' AlternateText='<%# getVideoTitleDesc(Eval("VideoDate"),Eval("VideoTitle"),Eval("VideoDesc")) %>' runat="server" CssClass="video-thumbnail" />
</div>
<div class="video-name">
<asp:Label ID="lblvideoName" CssClass="video-name-lbl" runat="server" Text='<%#Eval("VideoTitle") %>'></asp:Label>
</div>
<div class="video-issue">
<asp:Label ID="lblVideoIssue" CssClass="video-issue-lbl" runat="server" Text='<%#getIssuCode(Eval("IssueCode")) %>'></asp:Label>
</div>
</asp:HyperLink>
</div>
</ItemTemplate>
</asp:Repeater>
Based on the code above i am reinitializing fancy-box as i have updatePanel.
But i am not sure how i should make ajax call to updateHits.aspx?VideoID=xyzxvtmiw so that i can update database.
You could just add your AJAX call to the click event:
function InitMyFancyBox() {
$(document).ready(function () {
$(".youtube").click(function () {
// first, get the value from the alt attribute
var newTitle = $(this).find("img").attr("alt"); // Get alt from image
$.fancybox({
//...
});
// your Ajax call here
$.ajax({
type: "POST",
url: "updateHits.aspx?VideoID=xyzxvtmiw"
});
return false;
});
});
}
If you want the ajax call to be separate from the fancybox init you can just add another click handler somewhere else in your page:
$(".youtube").click(function () {
// your Ajax call here
$.ajax({
type: "POST",
url: "updateHits.aspx?VideoID=xyzxvtmiw"
});
}
I have Index view:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width" />
<title>MsmqTest</title>
</head>
<body>
<div>
<input type="submit" id="btnBuy" value="Buy" onclick="location.href='#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })'" />
<input type="submit" id="btnSell" value="Sell" onclick="location.href='#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })'" />
</div>
<div id="msmqpartial">
#{Html.RenderPartial("Partial1", Model); }
</div>
</body>
</html>
and partial:
#using System.Web.Mvc.Html
#model MsmqTestApp.Models.MsmqData
<p>
Items to buy
#foreach (var item in Model.ItemsToBuy)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
<p>
<a>Items Selled</a>
#foreach (var item in Model.ItemsSelled)
{
<tr>
<td>#Html.DisplayFor(model => item)
</td>
</tr>
}
</p>
And controller:
public class MsmqTestController : Controller
{
public MsmqData data = new MsmqData();
public ActionResult Index()
{
return View(data);
}
public ActionResult BuyItem()
{
PushIntoQueue();
ViewBag.DataBuyCount = data.ItemsToBuy.Count;
return PartialView("Partial1",data);
}
}
How to do that when i Click one of button just partial view render, now controller wants to move me to BuyItem view ;/
The first thing to do is to reference jQuery. Right now you have referenced only jquery.unobtrusive-ajax.min.js but this script has dependency on jQuery, so don't forget to include as well before it:
<script src="#Url.Content("~/Scripts/jquery.jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Now to your question: you should use submit buttons with an HTML form. In your example you don't have a form so it would be semantically more correct to use a normal button:
<input type="button" value="Buy" data-url="#Url.Action("BuyItem", "MsmqTest", new { area = "Msmq" })" />
<input type="button" value="Sell" data-url="#Url.Action("SellItem", "MsmqTest", new { area = "Msmq" })" />
and then in a separate javascript file AJAXify those buttons by subscribing to the .click() event:
$(function() {
$(':button').click(function() {
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
success: function(result) {
$('#msmqpartial').html(result);
}
});
return false;
});
});
or if you want to rely on the Microsoft unobtrusive framework you could use AJAX actionlinks:
#Ajax.ActionLink("Buy", "BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
#Ajax.ActionLink("Sell", "SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" })
and if you want buttons instead of anchors you could use AJAX forms:
#using (Ajax.BeginForm("BuyItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Buy</button>
}
#using (Ajax.BeginForm("SellItem", "MsmqTest", new { area = "Msmq" }, new AjaxOptions { UpdateTargetId = "msmqpartial" }))
{
<button type="submit">Sell</button>
}
From what I can see you have already included the jquery.unobtrusive-ajax.min.js script to your page and this should work.
Maybe not the solution you were looking for but, I would forget about partials and use Javascript to call the server to get the data required and then return the data to the client as JSON and use it to render the results to the page asynchronously.
The JavaScript function;
var MyName = (function () {
//PRIVATE FUNCTIONS
var renderHtml = function(data){
$.map(data, function (item) {
$("<td>" + item.whateveritisyoureturn + "</td>").appendTo("#msmqpartial");
});
};
//PUBLIC FUNCTIONS
var getData = function(val){
// call the server method to get some results.
$.ajax({ type: "POST",
url: "/mycontroller/myjsonaction",
dataType: "json",
data: { prop: val },
success: function (data) {
renderHtml();
},
error: function () {
},
complete: function () {
}
});
};
//EXPOSED PROPERTIES AND FUNCTIONS
return {
GetData : getData
};
})();
And on the Server....
public JsonResult myjsonaction(string prop)
{
var JsonResult;
// do whatever you need to do
return Json(JsonResult);
}
hope this helps....
I have created web service which I am calling from client script. But it shows an error. I can not understand where the error is coming from. I also set break points at different points both in web service and in client script but not encountered those break points. Here is the code that I have written.
Code for Class file
public class GetContacts
{
public int ID { get; set; }
public string Name { get; set; }
public GetContacts()
{
//
// TODO: Add constructor logic here
//
}
public List<GetContacts> FetchContacts()
{
List<GetContacts> ContactList = new List<GetContacts>();
ContactList.Add(new GetContacts() { ID = 1, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 2, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 3, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 4, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 5, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 6, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 7, Name = "XXX<1111111111>" });
ContactList.Add(new GetContacts() { ID = 7, Name = "XXX<1111111111>" });
return ContactList;
}
}
Code for web service.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Contacts : System.Web.Services.WebService {
public Contacts () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
public List<GetContacts> FetchContactList(string Name)
{
var Receipent = new GetContacts();
var ContactDetail = Receipent.FetchContacts()
.Where(m => m.Name.ToLower().StartsWith(Name.ToLower()));
return ContactDetail.ToList();
}
}
Code for Default.aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<%--<script src="jQuery.js" type="text/javascript"></script>--%>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "Contacts.asmx/FetchContactList",
data: "{ 'Name': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table width="100%">
<tr>
<td>
Number</td>
<td>
<asp:TextBox ID="txtNumber" runat="server" class="tb"></asp:TextBox>
</td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
Message</td>
<td>
<asp:TextBox ID="txtMsg" runat="server" TextMode="MultiLine"></asp:TextBox></td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnSend" runat="server" Text="Send" onclick="btnSend_Click" /></td>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</form>
</body>
</html>
Please tell me where I am making mistakes.
Add [WebMethod] attribute to your FetchContactList
have you implemented the attributes
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
See this for complete reference
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AutoComplete/AutoComplete.aspx