ajax post does not return view data - c#

I am using ajax post to call controller method DeviceData(). It does not return view data.
When I try to debug the code ,values are assigned to viewBag both in controller.cs and .cshtml but browser displays no data. Code does not return any error. After ajax call it only shows patientDDL.
I need to display "deviceName date etc.." which I assigned in viewBag.
This is my code:
DeviceData.cshtml
#model Hospital.Models.DeviceModel
<div class="row">
<div class="col-md-12">
<div id="pdf" class="pull-left">
<table>
<tr>
<td class="blue-bgcolor">Patient List : </td>
<td>
#Html.DropDownList("FromJson", new SelectList(Enumerable.Empty <SelectListItem>()),"select",
new { Class = "form-control", onchange = "SelectedIndexChanged()" })
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row">
<table class="table valign-middle">
<tbody>
<tr>
<td>Device Name</td>
<td>#ViewBag.deviceName</td>
</tr>
<tr>
<td>DateTime</td>
<td>#ViewBag.date</td>
</tr>
<tr>
<td>SPO2</td>
<td>#ViewBag.spo2</td>
</tr>
<tr>
<td>PR</td>
<td>#ViewBag.pr</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "PatinetDDl",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function(result) {
$(result).each(function() {
$("#FromJson").append($("<option></option>").val(this.Value).html(this.Text));
});
},
error: function(data) {}
});
});
</script>
<script type="text/javascript">
function SelectedIndexChanged() {
var pid = $("#FromJson").val();
alert(pid);
$.ajax({
url: '/Data/DeviceData',
type: 'POST',
datatype: 'json',
//contentType: 'application/json',
data: { pid: +pid },
success: function (result) { },
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
</script>
Datacontroller.cs
public JsonResult PatinetDDl()
{
Common.DBConnect.fnconchk(con);
DataTable dtpatient = new DataTable();
string query = "";
query = "select Preg_id,P_Name from Patient_Reg";
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dtpatient);
List<SelectListItem> ObjList = new List<SelectListItem>();
foreach (DataRow row in dtpatient.Rows)
{
ObjList.Add(new SelectListItem()
{
Text = row["P_Name"].ToString(),
Value = row["Preg_id"].ToString()
});
}
var jsonData = ObjList;
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult DeviceData()
{
DeviceModel obj = new DeviceModel();
return View(obj);
}
[HttpPost]
public ActionResult DeviceData(string pid)
{
DeviceModel obj = new DeviceModel();
DataTable dt = new DataTable();
Common.DBConnect.fnconchk(con);
if (pid != null)
{
string query = "";
query = " select D_Name,Date_Time,D_Value1 from readings where pid='" + pid;
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dt);
ViewBag.deviceName = dt.Rows[0]["D_Name"].ToString();
ViewBag.date = dt.Rows[0]["Date_Time"].ToString();
ViewBag.spo2 = dt.Rows[0]["D_Value1"].ToString();
ViewBag.pr = dt.Rows[0]["D_Value2"].ToString();
}
return View(obj);
}

Many things you want to change to get the desire output.
First
make a partial view name _deviceInfo.cshtml
<table class="table valign-middle">
<tbody>
<tr>
<td>Device Name</td>
<td>#ViewBag.deviceName</td>
</tr>
<tr>
<td>DateTime</td>
<td>#ViewBag.date</td>
</tr>
<tr>
<td>SPO2</td>
<td>#ViewBag.spo2</td>
</tr>
<tr>
<td>PR</td>
<td>#ViewBag.pr</td>
</tr>
</tbody>
</table>
Second
Changing in your controller action method
[HttpPost]
public PartialViewResult DeviceData(string pid)
{
DeviceModel obj = new DeviceModel();
DataTable dt = new DataTable();
Common.DBConnect.fnconchk(con);
if (pid != null)
{
string query = "";
query = " select D_Name,Date_Time,D_Value1 from readings where pid='" + pid;
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dt);
ViewBag.deviceName = dt.Rows[0]["D_Name"].ToString();
ViewBag.date = dt.Rows[0]["Date_Time"].ToString();
ViewBag.spo2 = dt.Rows[0]["D_Value1"].ToString();
ViewBag.pr = dt.Rows[0]["D_Value2"].ToString();
}
return PartialView(obj);
}
Third
Ajax Method in DeviceData.cshtml
#model Hospital.Models.DeviceModel
<div class="row">
<div class="col-md-12">
<div id="pdf" class="pull-left">
<table>
<tr>
<td class="blue-bgcolor">Patient List : </td>
<td>
#Html.DropDownList("FromJson", new SelectList(Enumerable.Empty <SelectListItem>()),"select",
new { Class = "form-control", onchange = "SelectedIndexChanged()" })
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row" id="device-data">
</div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "PatinetDDl",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function(result) {
$(result).each(function() {
$("#FromJson").append($("<option></option>").val(this.Value).html(this.Text));
});
},
error: function(data) {}
});
});
</script>
<script type="text/javascript">
function SelectedIndexChanged() {
var pid = $("#FromJson").val();
alert(pid);
$.ajax({
url: '/Data/DeviceData',
type: 'POST',
datatype: 'html',
//contentType: 'application/json',
data: { pid: +pid },
success: function (result) {
$('#device-data').html(result);
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
</script>
Hope it will work for you :)

The Problem is you return a view by action result (html) but you have used data type json in your second ajax script.
Edit SelectedIndexChanged like this :
function SelectedIndexChanged() {
var pid = $("#FromJson").val();
alert(pid);
$.ajax({
url: '/Data/DeviceData',
type: 'POST',
datatype: 'html',
//contentType: 'application/json',
data: { pid: +pid },
success: function (data) {
$('#placeHolder').html(data);
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
Don't forget to add placeHolder element where ever you want to show the DeviceData:
<div id="#placeHolder"></div>

Related

Ajax & ASP.NET MVC : get data by ID without using Entity Framework

I am trying to get data in my DataTable by ID, the data row coming from SQL Server to my controller but I am confused: how to pass this data to my DataTable in view?
I am using this code - my model:
public class EmployeesModel
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public int Age { get; set; }
public string Position { get; set; }
public string Office { get; set; }
[Required(ErrorMessage ="Please enter date")]
public DateTime HiringDate { get; set; }
public int Salary { get; set; }
}
My controller
public JsonResult GetEmpByID(int id)
{
List<EmployeesModel> employeeList = new List<EmployeesModel>();
string CS = ConfigurationManager.ConnectionStrings["SQLConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SP_GetEmpByID", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpID", SqlDbType.NVarChar).Value = id; //Added Parameter
conn.Open();
// Get
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EmployeesModel employee = new EmployeesModel();
employee.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);
employee.Name = reader["Name"].ToString();
employee.Gender = reader["Gender"].ToString();
employee.Age = Convert.ToInt32(reader["Age"]);
employee.Position = reader["Position"].ToString();
employee.Office = reader["Office"].ToString();
employee.HiringDate = Convert.ToDateTime(reader["HiringDate"]);
employee.Salary = Convert.ToInt32(reader["Salary"]);
employeeList.Add(employee);
}
}
//return View(employeeList); Commented out
//return RedirectToAction("GetEmpByID"); Commented out
return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
}
My view
#model IEnumerable<SQLWithoutEF.EmployeesModel>
<input type="text" id="tablename" /> //Here I enter Employee ID and below is button
<asp:Button runat="server" Text="Button" class="btn btn-danger" id="IDbtn" onclick="GetByName($('#tablename').val())">Get Data By ID</asp:Button>
#*Data Table ==============*#
<table class="table table-bordered table-responsive table-hover" id="MyTable">
<thead>
<tr>
<th style="display:none">#Html.DisplayNameFor(m => m.EmployeeId)</th>
<th>#Html.DisplayNameFor(m => m.Name)</th>
<th>#Html.DisplayNameFor(m => m.Gender)</th>
<th>#Html.DisplayNameFor(m => m.Age)</th>
<th>#Html.DisplayNameFor(m => m.Position)</th>
<th>#Html.DisplayNameFor(m => m.Office)</th>
<th>#Html.DisplayNameFor(m => m.HiringDate)</th>
<th>#Html.DisplayNameFor(m => m.Salary)</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var employee1 in Model)
{
<tr>
<td style="display:none">#employee1.EmployeeId</td>
<td>#employee1.Name</td>
<td>#employee1.Gender</td>
<td>#employee1.Age</td>
<td>#employee1.Position</td>
<td>#employee1.Office</td>
<td>
#if (employee1.HiringDate != null)
{
#employee1.HiringDate
}
</td>
<td>#employee1.Salary</td>
<td>
<asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> |
<asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button>
</td>
</tr>
}
</tbody>
</table>
My jQuery / Ajax - here I need help:
function GetByName(id) {
if (confirm("Are You Sure to Get " + id + " " + " ?")) {
$('#MyTable tbody tr').remove();
$.ajax({
type: "GET",
url: '/Home/GetEmpByID?id=' + id,
//data: JSON.stringify({ id: id }),
//contentType: application/json, charset: utf-8,
processData: false,
dataType: 'json',
bprocessing: true,
success: function (data) { // Till here data coming but it's not working further
var items = '';
$.each(data, function (item) {
debugger;
var rows = '';
for (var i = 0; i < item.length[0]; i++) {
rows = "<tr><td>" + data + "</td>"
+ '<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button></td>'
"</tr>";
$('#MyTable tbody').append(rows);
}
})
},
}).catch(function (xhr, status, error) {
var errorMeassage = xhr.status + ': ' + xhr.statusText;
alert('Error - ' + errorMeassage);
})
};
};
Here is the screenshot what output I am getting
enter image description here
Kindly suggest how I can send data from my controller to my DataTable using Ajax?
Thanks
From the controller API action,
return Json(new { data = employeeList }, JsonRequestBehavior.AllowGet);
It will return the response with body as an object with data property which contains the array, instead of the response is the array.
The response body would be as:
{
data: [/* Employee List */]
}
In JavaScript part, to take the employee array
var items = data.data;
The implementation in success callback should be:
var items = data.data;
$.each(items, function (index, item) {
debugger;
var rows = '';
rows = `<tr>
<td style="display:none">${item.EmployeeId}</td>
<td>${item.Name}</td>
<td>${item.Gender}</td>
<td>${item.Age}</td>
<td>${item.Position}</td>
<td>${item.Office}</td>
<td>${item.HiringDate}
</td>
<td>${item.Salary}</td>
<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="${item.Name}" id="deletebtn" onclick="deleteF(${item.EmployeeId}">DeleteEmp</asp:button></td>
</tr>`;
$('#MyTable tbody').append(rows);
})
Note: You may use the string interpolation / template literal which makes it easier to build the template string.
Demo

Values from Json for Jquery autocomplete

I'm a fairly new to JQuery, Json, and MVC. I am trying to a get the autocomplete to work in a text-box (with a drop-down). This is for a parameter value selection used in a web report. The data-table values are in the model called 'BSNList'. THen in the .cshtml View, the BSN text values have to be put to a var for the jquery function to run the autocomplete - I have it working with a inline list to test the autocomplete. But, I can't get the BSNList values to work in the jquery script- even trying with a JsonConvert.SerializeObject here is my code
birthCertificateModel.BSNList = new SelectList(_jobsParamData.AsDataView(), "JobId", "BSN");
birthCertificateModel.JSONresult = JsonConvert.SerializeObject(_jobsParamData);
return View(birthCertificateModel);
<div class="col-md-2">
#*<div class="ui-widget">*#
<label for="tags">BSNs: </label>
<input id="tags" class="ui-autocomplete-input" name="tags">
#*</div>*#
#Html.LabelFor(m => m.BSNName, ReportCaptions.BSN) <br />
#Html.ListBoxFor(m => m.BSNName,
Model.BSNList,
new { #class = "ListBox", size = 8 })
</div>
<script type="text/javascript">
var jsonBSNList;
jsonBSNList = #Model.BSNList.DataTextField;
$(document).ready(function () {
$(function () {
$("#tags").autocomplete({
source: jsonBSNList
});
});
});
`
Figured this out - here is my controller , html and script - I think the ajax is where I stumbled first.
[HttpPost]
public JsonResult SerialNumberLookup(string serialNumberString)
{
using (SqlConnection conn = new SqlConnection(this.connstr))
{
List<string> serialNumberList = new List<string>();
using (SqlCommand cmd =
new SqlCommand(BuildJobStatusModel.LookupSQLSelect, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#SearchText", serialNumberString);
SqlDataReader sqlDataReader = cmd.ExecuteReader();
while (sqlDataReader.Read())
{
serialNumberList.Add(sqlDataReader["SerialNumber"].ToString());
}
return this.Json(serialNumberList, JsonRequestBehavior.AllowGet);
}
}
<br />
#Html.LabelFor(model => model.SelectedSerialNumber, ReportCaptions.SerialNumber + " Look-up:")
#Html.TextBoxFor(model => model.SelectedSerialNumber, htmlAttributes: new { #id = "autocompleteSerialNumber" })
<br />
$("#autocompleteSerialNumber").autocomplete(
{
minLength: minSearchLen,
source: function (request, response) {
$.ajax({
url: "/Reports/SerialNumberLookup",
type: "POST",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data: { SerialNumberString: request.term },
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
value: item
};
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
})
}
});

Program couldnt find the path Partial view

I have a dropdownlist that when someone select some item in dropdown it need to be render partial and that partial loading some checkboxes.I trying to render partial but it keeps throwing not found error.I'm sure about path
Is it related with Html.Partial or Html.RenderPartial ?
My Controller:
[HttpGet]
public ActionResult SendCheckList(string input)
{
if (String.IsNullOrEmpty(input))
return null;
FormDetailViewModel model = new FormDetailViewModel();
int id =Convert.ToInt32(input);
ItemsRepository items = new ItemsRepository();
CheckListRepository checkListRep = new CheckListRepository();
CheckList checkList = db.CheckLists.FirstOrDefault(t =>
t.CheckListTypeId == id);
List<Item> İtems = db.Items.Where(t => t.ItemId ==
checkList.ItemId).ToList();
foreach (Item item in İtems)
{
İtemList.Add(new SelectListItem { Value =
item.ItemId.ToString(), Text = item.ItemDesc });
}
model.İtems = İtemList;
return PartialView
("~/Areas/User/Views/FormDetail/SendCheckList.cshtml", model);
}
My View:
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"
type="text/javascript"></script>
<script src="~/Content/js/open.js"></script>
#using (Html.BeginForm())
{
<table class="table table-hover">
<tr>
<td>
#Html.DisplayNameFor(model => model.FormDetail.CheckListType)
</td>
<td>
#Html.DropDownListFor(model => model.FormDetail.CheckListTypeId,
Model.checkLists, new { #id = "Selection", #class = "drop-open"})
</td>
</tr>
Js/Jquery:
$(document).ready(function () {
$('#Selection').on('change', function () {
$('#results').load('#Html.RenderPartial("~/Areas/User/Views/FormDetail/
SendCheckList.cshtml")')
});
});
The following code works for me. You need to make some changes in the JQuery.
public ActionResult SendCheckList(string input)
{
---
---
---
return PartialView("~~/Areas/User/Views/FormDetail/SendCheckList.cshtml", mode);
}
JQuery
$(document).ready(function () {
$('#Selection').on('change', function () {
var obj = {};
obj.parameter = parameter;
$.ajax({
url: '/ControllerName/SendCheckList',
data: JSON.stringify(obj),
contentType: 'application/json; charset=utf-8',
cache: false,
type: 'POST',
datatype: 'json',
async: false
})
.success(function (data) {
$("#DivID").html(data);
});
});
);

Remove From Cart operation not rendering anything

I got an issue with my Ajax. When I clicked on the Remove From Cart, The ajax seems not rendering anything. Any hint? Here is my code:
Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
});
return false;
});
});
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description,"Details", "Panier", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.ProduitId">
#item.Quantite
</td>
<td>
Remove From Cart
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
PanierController.cs
// AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
ShoppingCart.cs
public int RemoveFromCart(int id)
{
// Get the cart
var cartItem = db.Paniers.Single(
cart => cart.CartId == ShoppingCartId
&& cart.ProduitId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Quantite > 1)
{
cartItem.Quantite--;
itemCount = cartItem.Quantite;
}
else
{
db.Paniers.Remove(cartItem);
}
// Save changes
db.SaveChanges();
}
return itemCount;
Here is the Chrome output PF12 for the network tab
Change:
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
To:
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
type: 'POST',
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
Another option, although not recommended is to remove the [HttpPost] from the top of your controller. This will raise other issues for you, as the recommended way to send data using ajax is 'POST'

autocomplete jquery asp.net c#

my database table TAGS(TagId,TagName) my web method code is as follows
public List<Tag> FetchTagList(string tag)
{
OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"|DataDirectory|\\ImageDB2.mdb\";Persist Security Info=True");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string query = "select * from TAGS Where TagName like '#myParameter'";
OleDbCommand cmd = new OleDbCommand(query,cn);
cmd.Parameters.AddWithValue("#myParameter", "%" + tag + "%");
try
{
cn.Open();
cmd.ExecuteNonQuery();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds);
}
catch(OleDbException excp)
{
}
finally
{
cn.Close();
}
dt = ds.Tables[0];
List<Tag> Items = new List<Tag>();
Tag obj;
foreach (DataRow row in dt.Rows)
{
obj = new Tag();
//String From DataBase(dbValues)
obj.TagName = row["TagName"].ToString();
obj.ID = Convert.ToInt32(row["TagId"].ToString());
Items.Add(obj);
}
return Items;
}
}
i used class
public class Tag
{
public int ID { get; set; }
public string TagName { get; set; }
}
my javascript code is
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="jsautocom/jquery.min.js" type="text/javascript"></script>
<script src="jsautocom/jquery-ui.min.js" type="text/javascript"></script><script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "WebService.asmx/FetchTagList",
data: "{ 'tag': '" + 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.TagName
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1
});
});
</script>
my aspx page is as like
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Search Tag: </label>
<asp:TextBox ID="TextBox1" class="tb" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:Button ID="btnSearch" runat="server" CssClass="btnSearch"
onclick="btnSearch_Click" Text="Search" />
</div>
</div>
but i get nothing.how to solve it.any one helps me is greatly appreciated.thanks in advance
just change the data and response in the ajax as given below
data: "{'PhoneContactName':'" + document.getElementById("<%= ContactName.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
in your case change the PhoneContactName as something like the tag etc.,
hope this helps :D
There are 2 things to take care here:
A- make sure that you can call your service method, use [WebMethod] attribute over your function to make it available to be called over http.
you may also need to tune the WebService settings a little to make it to work.
B- Your javascript code is too much for this task.
considering what is written inside the official documentation of Autocomplete, you only need to point out 2 things:
Url of the fetching method,
The control that the user is going to write on, and will trigger the
autocomplete call using the current value inside.
Consider the following example:
$(".tb").autocomplete({source: "URL_OF_YOUR_REMOTE_METHOD"});
considering your example, you will need to put this code:
$(".tb").autocomplete({source: "WebService.asmx/FetchTagList"});
This is the minimal piece of code that you need in order to make it to work.
but to take everything manually as you did, is a little bit complicated and not that easy to figure our problem once they start to happen.
a live example: http://jsfiddle.net/grtWe/1/
just use this piece of code and let me know if it works, then we may go from here to achieve your goal.
if FetchTagList is your webmethod you are calling from jquery then don`t return list from method you can bind datatable directly to the autocomplete textbox just check following link how to do that.
http://nareshkamuni.blogspot.in/2012/06/sample-example-of-jquery-autocomplete.html
also you can do that using ajax autocomplete extender. for using ajax autocomplete extender refer following link
http://www.aspsnippets.com/Articles/ASPNet-AJAX-AutoCompleteExtender-Pass-Additional-Parameter-to-WebMethod-using-ContextKey.aspx
script is as follows:
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".auto").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Photos.aspx/GetAutoCompleteData",
data: "{'CategoryName':'" + document.getElementById("<%= txtCategory.ClientID %>").value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error Occurred");
}
});
}
});
}
</script>
web method:
[WebMethod]
public static List<string> GetAutoCompleteData(string CategoryName)
{
List<string> result = new List<string>();
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"|DataDirectory|\\ImageDB2.mdb\";Persist Security Info=True");
string query = "select TagName from TAGS where TagName LIKE '%" + CategoryName + "%'";
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
//cmd.Parameters.Add("#ptext", System.Data.SqlDbType.NVarChar).Value = CategoryName;
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["TagName"].ToString());
}
return result;
}
C# code
One thing need to remember here, Json data we cannot create manually, create using JavaScriptSerializer Class
<%# WebHandler Language="C#" Class="CountryStateCityHandler" %>
using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
public class CountryStateCityHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["action"] != null)
{
string strCallbackFunf = string.Empty;
if (context.Request.QueryString["callback"] != null)
{
strCallbackFunf = Convert.ToString(context.Request.QueryString["callback"]).Trim();
}
if (context.Request.QueryString["action"] == "getcountry")
{
DataTable dt = GetDataTable("EXEC PR_GetCountries"); //GetDataTable need to write, this method will call the Database and get the result
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
context.Response.ContentType = "text/plain";
if (string.IsNullOrEmpty(strCallbackFunf))
{
context.Response.Write(serializer.Serialize(rows));
}
else
{
context.Response.Write(strCallbackFunf+"("+serializer.Serialize(rows)+");");
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
//HTML CODE or .aspx code and script needs to be attached.
<html>
<head>
<script src="../scripts/jquery-1.7.js"></script>
<link href="../scripts/jqueryui/development-bundle/themes/smoothness/minified/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../scripts/jqueryui/js/jquery-ui-1.10.4.custom.min.js"></script>
<link href="../scripts/jqueryui/development-bundle/demos/demos.css" rel="stylesheet" type="text/css" />
<script language="JavaScript" type="text/javascript">
var CountriesTags; //Local variable to store json object
$(function () {
$("#lnkCountry")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.click(function () {
var wasOpen = $("#Country").autocomplete("widget").is(":visible");
$("#Country").autocomplete("widget").css("display", "none");
if (wasOpen) {
$("#Country").autocomplete("widget").css("display", "none");
return;
}
// Pass empty string as value to search for, displaying all results
$("#Country").autocomplete("search", "");
});
$("#Country").autocomplete({
source: function( request, response) {
var matcher = new RegExp("(^| )" + $.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(CountriesTags, function (item) {
return matcher.test(item.label);
}));
},
minLength: 0,
select: function (event, ui) {
var sv = ui.item.label;
var res = $.grep(CountriesTags, function (e, i) {
return e.label == sv;
});
if (res.length == 0) {
this.value = "";
$("#CountryID").val("");
alert(sv + " country is not available in database.");
}
else {
$("#CountryID").val(res[0].id);
}
},
change: function (event, ui) {
var sv = this.value;
var res = $.grep(CountriesTags, function (e, i) {
return e.label == sv;
});
if (res.length == 0) {
this.value = "";
$("#CountryID").val("");
alert(sv + " country is not available in database.");
}
else {
$("#CountryID").val(res[0].id);
}
},
});
LoadCountry();
}
//html inputs Value are country id (<%=CountryID %>) and country name (<%=Country%>)
function LoadCountry() {
$.ajax({
url: "CountryStateCityHandler.ashx?action=getcountry",
dataType: "jsonp",
type: 'GET',
async: false,
success: function (data) {
CountriesTags = data;
//array of Json Object will return
//label, value and id are keys
//Example id:219 label:"United States" value:"United States"
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + ' - Method: Loading countries - ' + thrownError);
}
});
}
</script>
</head>
<body>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
<input type="text" name="Country" id="Country" maxlength="50" size="20" class="TextBox" value="<%=Country%>" />
<input type="hidden" id="CountryID" name="CountryID" value="<%=CountryID %>">
</td>
<td>
<a style="height: 16px" id="lnkCountry"></a>
</td>
</tr>
</table>
</body>
</html>

Categories