Values from Json for Jquery autocomplete - c#

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);
}
})
}
});

Related

Autocomplete Ajax asp.net MVC, Display text

I am using Jquery with Ajax AutoComplete to return some data, but I'm kind of stuck with the display text.
This is what I have:
<script type="text/javascript">
$(document).ready(function () {
$("#locais").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("CreateF")',
datatype: "json",
data: {
s_localidade: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.remetente,
value: item.ID,
}
}))
}
})
},
});
});
And on controller:
public JsonResult CreateF(string s_localidade)
{
var tblOficiosExpedidos = db.tblOficiosExpedidos.Include(t => t.tblLocalidades);
var local = (from r in db.tblLocalidades
where r.Remetente.Contains(s_localidade.ToUpper())
select new { remetente = r.Remetente + " - " + r.Cidade, ID = r.LocalidadeID }).ToList();
return Json(local, JsonRequestBehavior.AllowGet);
}
On View:
#Html.TextBox("LocalidadeID","", htmlAttributes: new { #class = "form-control", #id="locais"})
It does work, but when i select an item, the text of the text box becomes the key number from my table. Is there a way to when i select something, the text keep as item.remetente but saves the number of item.ID into table?
You can do with the help of 'select'
try below approach
Your view
#Html.TextBox("LocalidadeID","", htmlAttributes: new { #class = "form-control", #id="locais"})
#Html.Hidden("hiddenlocais")
In your jquery define common function that takes both hidden and text box id as parameters
JQuery:
function WireUpAutoComplete(displayControlId, valueControlId)
{
$(displayControlId).autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("CreateF")',
datatype: "json",
data: {
s_localidade: request.term
},
select: function (event, ui) {
$(displayControlId).val(ui.item.Remetente);
$(valueControlId).val(ui.item.ID);
return false;
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.remetente,
value: item.ID,
}
}))
}
})
},
});
}
In document ready call above function
<script type="text/javascript">
$(document).ready(function () {
WireUpAutoComplete("#locais", "#hiddenlocais");
});
</script>
hope this solve your problem. i haven't tested. let me know if you face any problems

Posting files and model to controller in ASP.NET Core MVC6

I'm migrating a project from ASP.NET RC1 to ASP.NET Core 1.0.
I have a view that allows users to upload one of more files, which I post using Jquery Ajax. I also serialize and post some settings within the same post.
The following all worked in RC1 (and pre-asp.net core):
Js:
$('#submit').click(function () {
var postData = $('#fields :input').serializeArray();
var fileSelect = document.getElementById('file-select');
var files = fileSelect.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.each(postData, function (key, input) {
data.append(input.name, input.value);
});
var url = '/ajax/uploadfile';
$.ajax({
url: url,
type: "POST",
contentType: false,
processData: false,
cache: false,
data: data,
success: function (result) {
alert('success');
},
error: function () {
alert('error');
}
});
});
Controller:
public IActionResult UploadFile(UploadFileModel model)
{
var result = new JsonResultData();
try
{
if (Request.Form.Files.Count > 0)
{
IFormFile file = Request.Form.Files[0];
//etc
}
}
}
So the above does not work anymore, no file uploaded and no model bound.
I managed to fix half the issues so now I can get the model to bind with the following code. However, the controller will still give me an exception on the Request.Files. I added the 'headers' property, and I used serializeObject (custom method). In the controller I added FromBody.
Js:
$('#submit').click(function () {
var postData = $('#fields :input').serializeArray();
var fileSelect = document.getElementById('file-select');
var files = fileSelect.files;
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append('file' + i, files[i]);
}
$.each(postData, function (key, input) {
data.append(input.name, input.value);
});
var url = '/ajax/uploadfile';
$.ajax({
url: url,
type: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
processData: false,
cache: false,
data: serializeAndStingifyArray(data),
success: function (result) {
alert('success');
},
error: function () {
alert('error');
}
});
});
function serializeAndStingifyArray(array) {
var o = {};
var a = array;
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return JSON.stringify(o);
};
Controller:
[HttpPost]
public IActionResult UploadFile([FromBody]UploadFileModel model)
{
var result = new JsonResultData();
try
{
if (Request.Form.Files.Count > 0)
{
IFormFile file = Request.Form.Files[0];
//etc
}
}
}
html:
<div id="file-list">
<input type="file" name="file" class="file-select" accept="application/pdf,application">
<input type="file" name="file" class="file-select" accept="application/pdf,application" />
</div>
I started from this article which has some code that is almost the same as yours Upload Files In ASP.NET Core 1.0 (see Ajax case).
That worked for me fine on 1.0.0, so I implemented your changes and what I saw is that it failed to send the files in the request (client side issue).
This is how the payload should look like when working ok using F12 in chrome: (not sure why the file contents are hidden by chrome).
A little debugging and you are passing wrong data to data.append
The fix is in this line
$(".file-select").each(function () { data.append($(this).val(), $(this).get(0).files[0]); i++; })
Full code:
$(document).ready(function () {
$("#submit").click(function (evt) {
var data = new FormData();
i = 0;
$(".file-select").each(function () { data.append($(this).val(), $(this).get(0).files[0]); i++; })
var postData = $('#fields :input');
$.each(postData, function (key, input) {
data.append(input.name, input.value);
});
$.ajax({
type: "POST",
url: "/ajax/uploadfile", // <--- Double check this url.
contentType: false,
processData: false,
data: data,
success: function (message) {
alert(message);
},
error: function () {
alert("There was error uploading files!");
}
});
});
});
No need to use [FromBody] or serializeArray()
[HttpPost]
public IActionResult UploadFilesAjax(MyViewModel xxx )
{
This is my html, just in case:
<form method="post" enctype="multipart/form-data">
<div id="file-list">
<input type="file" name="file" class="file-select" accept="application/pdf,application">
<input type="file" name="file" class="file-select" accept="application/pdf,application" />
</div>
<div id="fields">
<input type="text" name="Email" />
</div>
<input type="button"
id="submit"
value="Upload Selected Files" />
</form>

TextBox to Auto-Fill

If a user is typing something into a textbox on a form, and what they are typing in starts to match a value that is already in the database, how do I get the textbox to give the option to auto-fill the rest of what the user wants to type in based on the value that is already in the database?
Consider I have this table(name of table: Person) in my database:
|ID| |FirstName| |LastName|
1 John Smith
2 Tom Jones
3 James Davis
and on the form where the user wants to create a new Person they start to type in jo into the FirstName textbox.. how do i get the textbox to give the option to autofill the hn and capitalize the first letter to spell John?
Any help is appreciated.
UPDATE:
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create([Bind(Include = "ID,text,subcategory")] Activity codeAC, string term)
{
if (ModelState.IsValid)
{
var result = (from r in db.Activities
where r.subcategory.ToUpper().Contains(term.ToUpper())
select new { r.subcategory }).Distinct();
db.Activities.Add(codeAC);
db.SaveChanges();
return Json(result, JsonRequestBehavior.AllowGet);
}
return Json(codeAC);
}
Script:
<script type="text/javascript">
$(document).ready(function () {
$('#Categories').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Activities/Create",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.subcategory, value: item.subcategory };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
CSHTML:
<div class="form-group">
#Html.LabelFor(model => model.subcategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.subcategory, new { htmlAttributes = new { #id = "Categories", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.subcategory, "", new { #class = "text-danger" })
</div>
</div>
I figured it out. I didn't know that I couldn't incorporate this into my Create ActionResult.. so I created a separate JsonResult method and it is working.
Controller:
public JsonResult AutoCompleteCategory(string term)
{
var result = (from r in db.Activities
where r.subcategory.ToUpper().Contains(term.ToUpper())
select new { r.subcategory }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
SCRIPT:
<script type="text/javascript">
$(document).ready(function () {
$('#Categories').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Activities/AutoCompleteCategory",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.subcategory, value: item.subcategory };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>

Ajax FileUpload & JQuery formData in ASP.NET MVC

I have some problem with posting formData to server side action method. Because ajax call doesn't send files to server, I have to add file uploader data to formData manually like this:
var formData = new FormData();
formData.append("imageFile", $("#imageFile").file);
formData.append("coverFile", $("#coverFile").file);
I wrote jQuery function that need to post form data to server using ajax call.
It's works but posted formData in server side is always null!
this is my script:
<script>
function SubmitButtonOnclick()
{
var formData = new FormData();
formData.append("imageFile", $("#imageFile").file);
formData.append("coverFile", $("#coverFile").file);
$.ajax({
type: "POST",
url: '#Url.Action("EditProfile", "Profile")',
data: formData,
dataType: 'json',
contentType: "multipart/form-data",
processData: false,
success: function (response) {
$('#GeneralSection').html(response.responseText);
},
error: function (error) {
$('#GeneralSection').html(error.responseText);
}
});
}
</script>
Edit 1:
This is the action method in controller:
public ActionResult EditProfile(ProfileGeneralDescription editedModel,
HttpPostedFileBase imageFile,
HttpPostedFileBase coverFile,
string postOwnerUser)
{
try
{
if (postOwnerUser == User.Identity.Name)
{
// edit codes...
var result = GetProfileGeneralDescription(postOwnerUser);
return PartialView("_GeneralProfile", result);
}
else
{
var error = new HandleErrorInfo(
new Exception("Access Denied!"),
"Profile",
EditProfile
return PartialView("~/Views/Shared/Error.cshtml", error);
}
}
catch (Exception ex)
{
var error = new HandleErrorInfo(ex, "Profile", EditProfile
return PartialView("~/Views/Shared/Error.cshtml", error);
}
}
Edit 2:
Cshtml view file content:
#model Website.Models.ViewModel.Profile
#using (Ajax.BeginForm("EditProfile", "Profile", new { postOwnerUser = User.Identity.Name }, new AjaxOptions()
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "GeneralSection"
}, new { enctype = "multipart/form-data" }))
{
<div>
<button id="btnSubmit" type="button" onclick="SubmitButtonOnclick()">Submit</button>
</div>
<input type="hidden" name="username" id="username" value="#Model.Username"/>
<fieldset>
<legend>Edit Photos</legend>
<div>
Select profile picture:
<input id="imageFile" type="file" name="imageFile" accept="image/png, image/jpeg" />
#Html.CheckBoxFor(modelItem => modelItem.DefaultCover)<span>Remove profile photo</span>
</div>
<div>
Select cover picture:
<input id="coverFile" type="file" name="coverFile" accept="image/png, image/jpeg" />
#Html.CheckBoxFor(modelItem => modelItem.DefaultCover)<span>RemoveCover</span>
</div>
</fieldset>
}
Any tips, link or code example would be useful.
Thank you in advance!
Instead of Jquery Ajax you could use
<script>
function SubmitButtonOnclick()
{
var formData= new FormData();
var imagefile=document.getElementById("imageFile").files[0];
var coverfile=document.getElementById("coverFile").files[0];
formData.append("imageFile",imageFile);
formData.append("coverFile",coverFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Profile/EditProfile", true);
xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
xhr.send(formData);
}
function UploadComplete(evt) {
if (evt.target.status == 200)
alert("Logo uploaded successfully.");
else
alert("Error Uploading File");
}
function UploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
</script>
This works for me !!
Your script with changes
function SubmitButtonOnclick() {
var formData = new FormData();
var file = document.getElementById("imageFile").files[0];
var file1 = document.getElementById("coverFile").files[0];
formData.append("imageFile", file);
formData.append("coverfile", file1);
$.ajax({
type: "POST",
url: '#Url.Action("EditProfile","Default1")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
$('#GeneralSection').html(response.responseText);
},
error: function (error) {
$('#GeneralSection').html(error.responseText);
}
});
}
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
I was able to upload file through jquery using the iframe, I explained the same in my blog post, please follow the link to get the answer.
http://kaushikghosh12.blogspot.com/2014/02/ajax-fileupload-on-all-browsers.html

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