I have a simple MVC application in which I am displaying data from the controller. and I want to show new data derieved from the call to the controller method.In other words, I am setting some default data to the html table and I want to change it using an Ajax call on button click. How can I do this, I can Share the code as follows :
The Model is :
public class Employee
{
public string Name { get; set; }
public string Surname { get; set; }
}
The Controller is :
public class SendAjaxParameterController : Controller
{
// GET: SendAjaxParameter
public ActionResult GetTheData()
{
List<Employee> Employee_Details = new List<Employee>();
Employee_Details = DefaultValues();
return View(Employee_Details);
}
public List<Employee> DefaultValues()
{
List<Employee> Employee_Details = new List<Employee>();
Employee emp = new Employee
{
Name = "John",
Surname = "Doe"
};
Employee emp1 = new Employee
{
Name = "Mary",
Surname = "Addinson"
};
Employee_Details.Add(emp);
Employee_Details.Add(emp1);
return Employee_Details;
}
[HttpPost]
public ActionResult Ajax_GetParameter(string name)
{
string nameofEmp = name;
List<Employee> Employee_Details = new List<Employee>();
if (name == "Monica")
{
Employee emp = new Employee
{
Name = "John",
Surname = "Doe"
};
Employee emp1 = new Employee
{
Name = "Mary",
Surname = "Addinson"
};
Employee_Details.Add(emp);
Employee_Details.Add(emp1);
}
else
{
Employee emp = new Employee
{
Name = "Robert",
Surname = "Doe"
};
Employee emp1 = new Employee
{
Name = "Monica",
Surname = "Addinson"
};
Employee_Details.Add(emp);
Employee_Details.Add(emp1);
}
return Json(new { success = true, data = Employee_Details },JsonRequestBehavior.AllowGet);
}
}
The View is :
#model IEnumerable<datatableViewTocontroller.Models.Employee>
#{
ViewBag.Title = "GetTheData";
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>GetData</title>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<link href="~/Scripts/datatable/DataTables-1.10.20/css/dataTables.jqueryui.min.css" rel="stylesheet" />
#section Scripts{
<script src="~/Scripts/datatable/DataTables-1.10.20/js/jquery.dataTables.min.js"></script>
<script src="~/Scripts/datatable/DataTables-1.10.20/js/dataTables.jqueryui.min.js"></script>
<script>
var nameValue = "";
var dttable = $("#mytable").DataTable();
$("#btn_GetData").click(function () {
if (confirm("Do you want to continue?")) {
nameValue = "Monica";
$.ajax({
type: "POST",
url: "/SendAjaxParameter/Ajax_GetParameter",
data: '{name:"' + nameValue + '"}',
contentType: "application/json; utf-8",
dataType: "json",
success: function (data) {
if (data.success) {
alert(data);
}
}
});
}
else {
nameValue = "Not Monica";
$.ajax({
type: "POST",
url: "/SendAjaxParameter/Ajax_GetParameter",
data: '{name:"' + nameValue + '"}',
contentType: "application/json; utf-8",
dataType: "json",
success: function (data) {
}
});
}
});
</script>
}
</head>
<body>
<div id="table-div">
<table id="mytable">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
#foreach (var modeldata in Model)
{
<tr>
<td>#modeldata.Name</td>
<td>#modeldata.Surname</td>
</tr>
}
</tbody>
</table>
</div>
<br />
<button id="btn_GetData" style="float:right;">GetData</button>
</body>
</html>
So, The question is How can I assign new data to the table ? Please Help!
You can use each loop to iterate through your json data which you have recieve from server and then use += to append new row to some variable.Then to add these row to your tbody you can use .html().
Demo Code :
//your response
var data = [{
"Name": "abc",
"Surname": "xyz"
}, {
"Name": "abcd",
"Surname": "xyzd"
}]
var html = "";
//loop through data
$.each(data, function(index, value) {
//append row
html += '<tr><td>' + value.Name + '</td>' + '<td>' + value.Surname + '</td><td><button name="edit">Edit</button></td></tr>';
});
//add row to tbody
$("#mytable tbody").html(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="table-div">
<table id="mytable">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!--data will come here-->
<tr>
<td>#modeldata.Name</td>
<td>#modeldata.Surname</td>
</tr>
</tbody>
</table>
</div>
I think the only problem is to clear the previously loaded data. You can clear the div retaining that data and then load the retrieved data using jQuery:
$('#div-or-row-id').html(""); //Clear div
On the other hand, you can also try the following approach or replace the table data by setting table data by response of AJAX call:
$.ajax({
//code omitted for brevity
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
SetData(data);
},
error: function (data) { onError(data); }
});
function SetData(data) {
$("#div-or-row-id").html(data); // HTML DOM replace
}
You can rerender table structure using Jquery after Ajax success call.
Just make Table Td structure and append in the respective div.
e.g.
$('You Parent div').empty().append('new structure');
as per your answer I've updated the code like :
$.ajax({
type: "POST",
url: "/SendAjaxParameter/Ajax_GetParameter",
data: '{name:"' + nameValue + '"}',
contentType: "application/json; utf-8",
dataType: "json",
success: function (data) {
if (data.success) {
alert(data);
var len = data.length;
var txt = "";
if (len > 0)
{
for (i = 0; i < len; i++) {
if(i==0){
txt +="<table id='mytable'>" +
"<thead>" +
"<tr>" +
"<th>Name</th>" +
"<th>Surname</th>" +
"</tr>" ;
}
txt += "<tr><td>" + data[i].Name + "</td><td>" + data[i].Surname + "</td></tr>"
}
if (txt != "") {
$("#mytable").empty().append(txt).removeClass("hidden");
}
}
}
}
});
Related
Basically Below Script and related Action Result worked in in ASP.Net but does not work in ASP.Net-Core 2.2 or 3.0.
Apparently Newtosoft JSON is not fully Supported in ASP.Net-Core 3.0 or I do not know how convert for use.
I am not getting an Error ..., The Form just never populates.
I have Copied View and Controllers between .Net version with the same result.
Controller:
public ActionResult GetProductByID1(string id)
{
int AvProdId = Convert.ToInt32(id);
// According id to query the database and get the relevant values.
var query = _context.AvProducts.Where(c => c.AvProductId == AvProdId)
.Select(c =>
new
{
c.AvProductId,
ProductName = c.ProductName,
ProductDesc = c.ProductDesc,
ProductComplexityFac = c.ProductComplexityFac,
ProductComplexityBase = c.ProductComplexityBase,
TotalComplexity = c.TotalComplexity,
Component1Desc = c.Component1Desc,
Component2Desc = c.Component2Desc,
Component3Desc = c.Component3Desc,
Component4Desc = c.Component4Desc,
Component5Desc = c.Component5Desc,
Component6Desc = c.Component6Desc,
Component7Desc = c.Component7Desc,
Component8Desc = c.Component8Desc,
Component9Desc = c.Component9Desc,
Component10Desc = c.Component10Desc,
Component11Desc = c.Component11Desc,
Component12Desc = c.Component12Desc,
Component13Desc = c.Component13Desc,
Component14Desc = c.Component14Desc,
Component15Desc = c.Component15Desc,
ComponentComplexityFac1 = c.ComponentComplexityFac1,
ComponentComplexityFac2 = c.ComponentComplexityFac2,
ComponentComplexityFac3 = c.ComponentComplexityFac3,
ComponentComplexityFac4 = c.ComponentComplexityFac4,
ComponentComplexityFac5 = c.ComponentComplexityFac5,
ComponentComplexityFac6 = c.ComponentComplexityFac6,
ComponentComplexityFac7 = c.ComponentComplexityFac7,
ComponentComplexityFac8 = c.ComponentComplexityFac8,
ComponentComplexityFac9 = c.ComponentComplexityFac9,
ComponentComplexityFac10 = c.ComponentComplexityFac10,
ComponentComplexityFac11 = c.ComponentComplexityFac11,
ComponentComplexityFac12 = c.ComponentComplexityFac12,
ComponentComplexityFac13 = c.ComponentComplexityFac13,
ComponentComplexityFac14 = c.ComponentComplexityFac14,
ComponentComplexityFac15 = c.ComponentComplexityFac15
})
.FirstOrDefault();
return Json(query);
}
Script: from View that populates User form based on DropDownlist Selection
#* Product #1 Calc*#
<script type="text/javascript">
$(function () {
$("#AvProductId").change(function () {
// alert($(this).val() + " " + $(this).find("option:selected").html());
var id = $(this).val();
$.ajax({
type: "Post",
url: '#Url.Action("GetProductByID1", "SizingUserDashBoard")',
data: '{id: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(data.LastName);
//$("#txtAvProdId").val(data.AvProductId);
//$("#txtProductName1").val(data.ProductName);
//$("#txtProductDesc1").val(data.ProductDesc);
//$("#txtProductComplexityFac1").val(data.ProductComplexityFac);
//$("#txtProductComplexityBase1").val(data.ProductComplexityBase);
//$("#txtTotalComplexity1").val(data.TotalComplexity);
//$("#txtComponent1Desc1").val(data.Component1Desc);
//$("#txtComponent2Desc1").val(data.Component2Desc);
//$("#txtComponent3Desc1").val(data.Component3Desc);
//$("#txtComponent4Desc1").val(data.Component4Desc);
//$("#txtComponent5Desc1").val(data.Component5Desc);
//$("#txtComponent6Desc1").val(data.Component6Desc);
//$("#txtComponent7Desc1").val(data.Component7Desc);
//$("#txtComponent8Desc1").val(data.Component8Desc);
//$("#txtComponent9Desc1").val(data.Component9Desc);
//$("#txtComponent10Desc1").val(data.Component10Desc);
//$("#txtComponent11Desc1").val(data.Component11Desc);
//$("#txtComponent12Desc1").val(data.Component12Desc);
//$("#txtComponent13Desc1").val(data.Component13Desc);
//$("#txtComponent14Desc1").val(data.Component14Desc);
//$("#txtComponent15Desc1").val(data.Component15Desc);
#* $("#TestProdDesc12").val(data.Component12Desc);
$("#TestProdDesc13").val(data.Component13Desc);
$("#Prod1Compnent2Desc").val($("#txtComponent2Desc1").val());
$("#Prod1Compnent3Desc").val($("#txtComponent3Desc1").val());*#
//$("#TestProdDesc12").val($("#txtComponent12Desc1").val());
//$("#TestProdDesc13").val($("#txtComponent13Desc1").val());
$("#DescProduct_1").val(data.ProductName);
$("#Prod1Compnent1Desc").val(data.Component1Desc);
$("#Prod1Compnent2Desc").val(data.Component2Desc);
$("#Prod1Compnent3Desc").val(data.Component3Desc);
$("#Prod1Compnent4Desc").val(data.Component4Desc);
$("#Prod1Compnent5Desc").val(data.Component5Desc);
$("#Prod1Compnent6Desc").val(data.Component6Desc);
$("#Prod1Compnent7Desc").val(data.Component7Desc);
$("#Prod1Compnent8Desc").val(data.Component8Desc);
$("#Prod1Compnent9Desc").val(data.Component9Desc);
$("#Prod1Compnent10Desc").val(data.Component10Desc);
$("#Prod1Compnent11Desc").val(data.Component11Desc);
$("#Prod1Compnent12Desc").val(data.Component12Desc);
$("#Prod1Compnent13Desc").val(data.Component13Desc);
$("#Prod1Compnent14Desc").val(data.Component14Desc);
$("#Prod1Compnent15Desc").val(data.Component15Desc);
$("#Compnent1Desc").val(data.Component1Desc);
$("#Compnent2Desc").val(data.Component2Desc);
$("#Compnent3Desc").val(data.Component3Desc);
$("#Compnent4Desc").val(data.Component4Desc);
$("#Compnent5Desc").val(data.Component5Desc);
$("#Compnent6Desc").val(data.Component6Desc);
$("#Compnent7Desc").val(data.Component7Desc);
$("#Compnent8Desc").val(data.Component8Desc);
$("#Compnent9Desc").val(data.Component9Desc);
$("#Compnent10Desc").val(data.Component10Desc);
$("#Compnent11Desc").val(data.Component11Desc);
$("#Compnent12Desc").val(data.Component12Desc);
$("#Compnent13Desc").val(data.Component13Desc);
$("#Compnent14Desc").val(data.Component14Desc);
$("#Compnent15Desc").val(data.Component15Desc);
$("#Prod1ComponentComplexityFac1_1").val(data.ComponentComplexityFac1);
$("#Prod1ComponentComplexityFac2_1").val(data.ComponentComplexityFac2);
$("#Prod1ComponentComplexityFac3_1").val(data.ComponentComplexityFac3);
$("#Prod1ComponentComplexityFac4_1").val(data.ComponentComplexityFac4);
$("#Prod1ComponentComplexityFac5_1").val(data.ComponentComplexityFac5);
$("#Prod1ComponentComplexityFac6_1").val(data.ComponentComplexityFac6);
$("#Prod1ComponentComplexityFac7_1").val(data.ComponentComplexityFac7);
$("#Prod1ComponentComplexityFac8_1").val(data.ComponentComplexityFac8);
$("#Prod1ComponentComplexityFac9_1").val(data.ComponentComplexityFac9);
$("#Prod1ComponentComplexityFac10_1").val(data.ComponentComplexityFac10);
$("#Prod1ComponentComplexityFac11_1").val(data.ComponentComplexityFac11);
$("#Prod1ComponentComplexityFac12_1").val(data.ComponentComplexityFac12);
$("#Prod1ComponentComplexityFac13_1").val(data.ComponentComplexityFac13);
$("#Prod1ComponentComplexityFac14_1").val(data.ComponentComplexityFac14);
$("#Prod1ComponentComplexityFac15_1").val(data.ComponentComplexityFac15);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve Products.');
}
});
});
});
</script>
You need to lowercase initial letter of data.property and change the url like below:
#section Scripts{
<script type="text/javascript">
$(function () {
$("#AvProductId").change(function () {
var id = $(this).val();
$.ajax({
type: "Post",
url: '#Url.Action("GetProductByID1", "SizingUserDashBoard")'+'?id='+id,
//data: '{id: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
$("#DescProduct_1").val(data.productName);
$("#Prod1Compnent1Desc").val(data.component1Desc);
$("#Prod1Compnent2Desc").val(data.component2Desc);
$("#Prod1Compnent3Desc").val(data.component3Desc);
$("#Prod1Compnent4Desc").val(data.component4Desc);
$("#Prod1Compnent5Desc").val(data.component5Desc);
$("#Prod1Compnent6Desc").val(data.component6Desc);
$("#Prod1Compnent7Desc").val(data.component7Desc);
$("#Prod1Compnent8Desc").val(data.component8Desc);
$("#Prod1Compnent9Desc").val(data.component9Desc);
$("#Prod1Compnent10Desc").val(data.component10Desc);
$("#Prod1Compnent11Desc").val(data.component11Desc);
$("#Prod1Compnent12Desc").val(data.component12Desc);
$("#Prod1Compnent13Desc").val(data.component13Desc);
$("#Prod1Compnent14Desc").val(data.component14Desc);
$("#Prod1Compnent15Desc").val(data.component15Desc);
$("#Prod1ComponentComplexityFac1_1").val(data.componentComplexityFac1);
$("#Prod1ComponentComplexityFac2_1").val(data.componentComplexityFac2);
$("#Prod1ComponentComplexityFac3_1").val(data.componentComplexityFac3);
$("#Prod1ComponentComplexityFac4_1").val(data.componentComplexityFac4);
$("#Prod1ComponentComplexityFac5_1").val(data.componentComplexityFac5);
$("#Prod1ComponentComplexityFac6_1").val(data.componentComplexityFac6);
$("#Prod1ComponentComplexityFac7_1").val(data.componentComplexityFac7);
$("#Prod1ComponentComplexityFac8_1").val(data.componentComplexityFac8);
$("#Prod1ComponentComplexityFac9_1").val(data.componentComplexityFac9);
$("#Prod1ComponentComplexityFac10_1").val(data.componentComplexityFac10);
$("#Prod1ComponentComplexityFac11_1").val(data.componentComplexityFac11);
$("#Prod1ComponentComplexityFac12_1").val(data.componentComplexityFac12);
$("#Prod1ComponentComplexityFac13_1").val(data.componentComplexityFac13);
$("#Prod1ComponentComplexityFac14_1").val(data.componentComplexityFac14);
$("#Prod1ComponentComplexityFac15_1").val(data.componentComplexityFac15);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve Products.');
}
});
});
});
</script>
}
Result:
in controller json method getting columnnames (Account,EmailTo,Subject,MessageContent) like this in ReportColumnsList ..but i need to pass these values in view page and display in listbox..
data is getting as [Object Object] and also displaying in listbox like this..
please give me solution regarding this..
Thanks & Regards
in Controller part :-
[AllowAnonymous]
public ActionResult GetColumnsByFavouriteReport(ReportsModel Model,string Columns)
{
List<Report> ReportColumnsList = MCPAdminControllerPageObject.GetColumnsByReportName(Columns);
return Json(ReportColumnsList, JsonRequestBehavior.AllowGet);
}
In view Part:-
$(document).ready(function () {
$('#FavouriteReports').change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetColumnsByFavouriteReport", "MCPAdmin")',
data: { Columns: $('#FavouriteReports').val() },
datatype: "json",
traditional: true,
success: function (data) {
$('#SelectedFields').empty();
$.each(data, function (key, val) {
$('#SelectedFields').append('<option id="' + key + '">' + val + '</option>');
})
}
});
});
#Html.ListBoxFor(m => m.SelectedFields, new SelectList(new[] { "" }), new { #class = "form-control editable" })
Let me assume Your model class Report
public class Report {
public int ReportId { get; set; }
public Name ReportName { get; set; }
}
Inside your ajax method
if(data!=null) {
$('#SelectedFields').empty();
var dd = null ;
$.each(data, function (key, val) {
dd += "<option " + " value=" + val.ReportId + ">" + val.ReportName + "</option>";
});
//append to given id
$('#SelectedFields').append(dd);
}
I hope this will help your, bind your dropdown list
im working on ASP.NET MVC 4 project. well i already insert data into a SQL Server database using jQuery using a post method in .
Now im trying to insert data into 2 tables using the same view, my problem is that i can't passing multiple POST parameters to Web API Controller Method. here is my js function and my controller code, ill apreciate your help
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient},
success: function (data) {
if(data==0) {
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1) {
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
Controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient: dataClient},
success: function (data) {
if(data==0){
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1){
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
//controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
you did not add dataClient: dataClient in ajax.
so please add this.
Hope this will help you.
Here is my j-son output and i want to access inner elements element.
how should i do that?
i have tried to access them in the following way
data[10];
but it didn't worked
public JsonResult ShowEventsList()
{
using (EventSchedularEntities db = new EventSchedularEntities())
{
var EventsList = from evnt in db.Events
select new
{
id = evnt.EventID,
Subject = evnt.EventName,
Description = evnt.EventDesc,
StartTime = evnt.EventDateBegin,
EndTime = evnt.EventDateEnd,
Color = evnt.Importance,
};
List<object[]> LstEvents = new List<object[]>();
foreach (var ev in EventsList)
{
LstEvents.Add(new object[] { ev.id, ev.Subject, ev.Description,DateTime.Parse(ev.StartTime.ToString()).ToString("M/dd/yyyy hh:mm").Replace("-", "/"), DateTime.Parse(ev.EndTime.ToString()).ToString("M/dd/yyyy hh:mm").Replace("-", "/"), ev.Color });
}
return Json( LstEvents, JsonRequestBehavior.AllowGet);
}
}
$.ajax({
type: "POST",
url: "../EventScheduler/ShowEventsList",
datatype: "json",
success: function (result)
{
var data = JSON.parse(result);
alert(data);
}
I am trying to follow this example
and I have the following in JSP page
(getData.jsp)
Department t = new Department ();
String query = request.getParameter("q");
List<String> tenders = t.getDepartments(query);
Iterator<String> iterator = tenders.iterator();
while(iterator.hasNext()) {
String deptName= (String)iterator.next();
String depto = (String)iterator.next();
out.println(deptName);
}
How can I use the above to use in Jquery autcomplete? When I tried there was no output coming.
My Jquery autoComplete code
<script>
$(function() {
$( "#dept" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getData.jsp",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.<??>, function( item ) {
return {
label: item.name + (item.<??> ? ", " + item.<??> : "") + ", " + item.<??>,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
alert(ui.item.label);
}
});
});
</script>
Is your response in JSON format?
Here's what I do when I use Jquery UI Autocomplete:
Create a class whose parameters are the ones you will use when you say item.name
public string Pam1{ get; set; }
public string Pam2{ get; set; }
public string Pam3{ get; set; }
public SomeResponse(string SomePam)
{
// Pam1 = ???
// Pam2 = ???
// Pam3 = ???
}
In your handler:
context.Response.ContentType = "application/json";
string query = (string)context.Request.QueryString["query"];
var json = new JavaScriptSerializer();
context.Response.Write(
json.Serialize(new SomeResponse(query))
);
context.Response.Flush();
context.Response.End();
EDIT
The javascript (Here is an example where the user can choose more than one option, separated by coma. If you don't want that, remove it.) txt_autocomplete is the class of the TextBox.
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$(".txt_autocomplete")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function (request, response) {
$.getJSON("handlers/autocomplete.ashx?query=" + extractLast(request.term), {
term: extractLast(request.term)
}, response);
},
search: function () {
var term = extractLast(this.value);
if (term.length < 2) {
return false;
}
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.Pam1);
terms.push("");
this.value = terms.join(", ");
console.log("Pam1 is :" + ui.item.Pam1 + " Pam2 is: " + ui.item.Pam2 + " Pam 3 is : " + ui.item.Pam3);
return false;
}
});
});