How can I use autocomplete in a jQuery in an each loop? - c#

I'm generating a table usinf jQuery. in each row I have an input field, that should search some values from DB usibg autocomplete. first row works perfectley but with the second I have problems, it returns in autocomplete only a value from the field above, I have no idea how can i fix it... can somebody help?
here is my code:
$.ajax({
type: "GET",
url: "/Home/JsonWeekEvents",
dataType: "JSON",
success: function (result) {
$.each(result, function (i, val) {
var trow = $('<tr/>').data("id", val.Id);
//trow.append('<td>' + val.Id + " " + '</td>');
trow.append('<td style="padding:5px; width:100px; height:70px"></td>');
trow.append('<td valign="top" style="padding:2px; width:150px; height:100px">' +
'<div class="ui-widget">' +
'<input size="10" maxlength="10" id="tagsM" class="tags" />' +
'<input type="button" id="addBtn" onclick="addEvent();" size="5" value="+" /><br/>' +
'<div style="text-align:center" id="desc_Num">' + val.Monday + '</div >' +
'</div >' +
'</td>');
tab.append(trow);
});
$("tr:odd", tab).css('background-color', '#C4C4C4');
$("#weekEvents").html(tab);
},
error: function () {
alert("Failed! Please try again.");
}
});
var tab = $('<table class=MyTable border=1 ></table>');
var thead = $('<thead></thead>');
thead.append('<th style="padding:5px">FSE' + " " + '</th>');
thead.append('<th style="padding:5px">Monday' + " " + '</th>');
thead.append('<th style="padding:5px">Tuesday' + " " + '</th>');
thead.append('<th style="padding:5px">Wednesday' + " " + '</th>');
thead.append('<th style="padding:5px">Thursday' + " " + '</th>');
thead.append('<th style="padding:5px">Friday' + " " + '</th>');
thead.append('<th style="padding:5px">Saturday' + " " + '</th>');
thead.append('<th style="padding:5px">Sunday' + " " + '</th>');
tab.append(thead);
tab.on("focus", "input[class='tags']", function (e) {
//var prefix = $('.tags').val();
$('.tags').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/GetSearchValue",
dataType: "json",
data: { search: $('.tags').val() },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Title + ', ' + item.Description, value: item.Title,
Id: item.Id,
Title: item.Title,
Description: item.Description,
Location: item.Location
}
}));
},
error: function (xhr, status, error) {
alert("Error!" + xhr);
},
});
}
});

Would advise something like the following:
tab.on("focus", "input[class='tags']", function(e) {
if (!$(this).hasClass("ui-autocomplete")) {
$(this).autocomplete({
source: function(request, response) {
$.getJSON("/Home/GetSearchValue", {
search: request.term
},
function(data) {
response($.map(data, function(item) {
return {
label: item.Title + ', ' + item.Description,
value: item.Title,
Id: item.Id,
Title: item.Title,
Description: item.Description,
Location: item.Location
}
}));
});
}
});
}
});
This will initialize autocomplete on focus event. If it's already initialized, that will not be repeated. The source will perform a GET request and search for the request.term from the User's input on that specific field.

Related

Populating DropdownList from AJAX (ASP.NET MVC)

I have dropdown list in my view
#Html.DropDownList("Question1", null, "Вопрос 1", htmlAttributes: new {#class = "form-control", #style = "height:40px;margin-bottom: 20px;"})
I have AJAX call that display all questions
Here it is
function question_update() {
$(".count").empty();
$.ajax({
url: '#Url.Action("QuestionsList", "Questions")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (result) {
var email = result;
var edit = '#Url.Content("~/Images/Edit.png")';
var delete_ = '#Url.Content("~/Images/Delete.png")';
// console.log(result[0].Name);
for (var i = 0; i <= email.length - 1; i++) {
var arrow = '#Url.Content("~/Images/plus_plus.png")';
var questionHtml = '<div class = "title" style="margin-top:15px;margin-left:15px;margin-bottom:10px;">'
+
'<img class="click" src="'
+ arrow
+ '">' +
'<span class="test">' +
'<input type="text" class="testclass" readonly value="' +
result[i].Quest + '">' +
'<a style="margin-left:25px;">' +
'<img src="' + edit + '"/>' +
'<img style="margin-left:10px;" src="' + delete_ + '"/>' +
'</div>' +
'<div class ="content" style="margin-left:60px; width: 80%; height: 100px; background: white;">' +
'<div style="width: 100%">' +
'<div style="float:left; width: 50%;">' +
'<b style="margin-left: 40px;">' + "Время на ответ" + '</b>' +
'<b>' + ":" + '</b>' +
'<span>' + "Время на подготовку" +'</span>'+
'</div>' +
'<div style="float:right; width: 50%;">' +
'<b>' + result[i].TimeForAnswer + '</b>' +
'<b>' + ":" + '</b>' +
'<b>' + result[i].TimeForReady + '</b>'+
'</div>' +
'</div>' +
'</div>';
$(".count").append(questionHtml);
At sucess of it I need to update values in dropdown
I make it like this
function question_update() {
$(".count").empty();
$.ajax({
url: '#Url.Action("QuestionsList", "Questions")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (result) {
var email = result;
var edit = '#Url.Content("~/Images/Edit.png")';
var delete_ = '#Url.Content("~/Images/Delete.png")';
// console.log(result[0].Name);
for (var i = 0; i <= email.length - 1; i++) {
var arrow = '#Url.Content("~/Images/plus_plus.png")';
var questionHtml = '<div class = "title" style="margin-top:15px;margin-left:15px;margin-bottom:10px;">'
+
'<img class="click" src="'
+ arrow
+ '">' +
'<span class="test">' +
'<input type="text" class="testclass" readonly value="' +
result[i].Quest + '">' +
'<a style="margin-left:25px;">' +
'<img src="' + edit + '"/>' +
'<img style="margin-left:10px;" src="' + delete_ + '"/>' +
'</div>' +
'<div class ="content" style="margin-left:60px; width: 80%; height: 100px; background: white;">' +
'<div style="width: 100%">' +
'<div style="float:left; width: 50%;">' +
'<b style="margin-left: 40px;">' + "Время на ответ" + '</b>' +
'<b>' + ":" + '</b>' +
'<span>' + "Время на подготовку" +'</span>'+
'</div>' +
'<div style="float:right; width: 50%;">' +
'<b>' + result[i].TimeForAnswer + '</b>' +
'<b>' + ":" + '</b>' +
'<b>' + result[i].TimeForReady + '</b>'+
'</div>' +
'</div>' +
'</div>';
$(".count").append(questionHtml);
$.ajax({
url: '#Url.Action(" QuestionsList_new", "Questions")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
processData: false,
success: function (result) {
var $vacancy = $("#Question1");
$vacancy.empty();
$.each(result, function (a, b) {
$vacancy.append('<option value="' + b.Value + '">' + b.Text + '</option>');
});
}
});
}
}
});
}
But I don't see any updates in DropdownList.
Where is my problem?
UPDATE
All okay. But I have new problem. In my dropdownlist I have undefined.
<select class="form-control" id="Question1" name="Question1" style="height:40px;margin-bottom: 20px;"><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option><option value="undefined">undefined</option></select>
How I can solve this?
Based on the sample data you gave for the result variable coming back from the server:
{ ID = 1048, Quest = "тест" }
your .each loop needs to look like this:
$.each(result, function (a, b) {
$vacancy.append('<option value="' + b.ID + '">' + b.Quest + '</option>');
});
The properties "text" and "value" that you were trying to access don't exist in the data, hence why you were getting "undefined". You need to use the names of the actual properties involved.

html table jQuery json value pass

I want to pass value through jQuery Json.The problem is that while passing the value then,it have some problem,thats why it is not calling c# code.
This is the html table:
$(function ()
{
debugger
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm7.aspx/BindCategoryDatatable",
data: "{}",
dataType: "json",
success: function (dt) {
debugger;
for (var i = 0; i < dt.d.length; i++) {
$("#tblid > tbody").append("<tr><td> <input type='checkbox' class='chk' id=" + dt.d[i].projectid + " /></td><td>" + dt.d[i].projectname + "</td><td>" + dt.d[i].Name + "</td><td>" + dt.d[i].technology + "</td><td>" + dt.d[i].projectliveurl + "</td><td><input type='image' src=" + dt.d[i].StatusImage + " onclick='actvstatus(" + dt.d[i].projectid + ", " + dt.d[i].status + ")' alt='Submit' width='18' height='18'> </td><td>" + dt.d[i].DisplayOrder + "</td><td> <i class='ui-tooltip fa fa-pencil' onclick='btnQueryString_Click(" + dt.d[i].projectid + ")' style='font-size:22px;margin-left: 32px;'></i><i class='ui-tooltip fa fa-trash-o' onclick='deleteRecord(" + dt.d[i].projectid + ")' style='font-size: 22px;margin-left: 32px;color:red'></i> </tr>");
}
$("#tblid").DataTable();
},
error: function (result) {
alert("Error");
}
});
});
This is my c# Code:
[WebMethod]
public static List<mProjects> BindCategoryDatatable(int catid)
{
clsProjectBL objcategory = new clsProjectBL();
List<mProjects> modelCategory = new List<mProjects>();
DataTable dtCategory = new DataTable();
//dtCategory = objcategory.GetAllCategoryDetails("admin");
dtCategory = objcategory.GetAllProjectDetails("admin", catid);
if (dtCategory.Rows.Count > 0)
{
modelCategory = (from DataRow dr in dtCategory.Rows
select new mProjects()
{
projectid = Convert.ToInt32(dr["projectid"]),
CategoryID = Convert.ToInt32(dr["CategoryID"]),
projectname = dr["projectname"].ToString(),
Name = dr["Name"].ToString(),
technology = dr["technology"].ToString(),
projectliveurl = dr["projectliveurl"].ToString(),
DisplayOrder = Convert.ToInt32(dr["DisplayOrder"]),
status = Convert.ToBoolean(dr["status"]),
StatusImage = dr["StatusImage"].ToString(),
//Deleted = Convert.ToBoolean(dr["Deleted"])
}).ToList();
}
return modelCategory;
}
The value is not pass through webmethod...
Your back-end required a parameter catid so you have to pass catid to AJAX call as #BenG and #palash answer with data attribute.
data: { catid: 1 }
Or you pass it to the url with format
url: "WebForm7.aspx/BindCategoryDatatable?catid=" + YOUR_ID.
Otherwise, it will not be worked because BindCategoryDatatable return an empty list.

Get next 8 rows from database on button click using linq to sql and web method

I am creating a webpage in which I fetch top 8 rows from database on page load. I put load more button on my bottom of my web page. What I want is when I click on load more button it shows me next new 8 rows and skip previous records and if there is no new record found then show me nothing.
Below is my code which I was trying but it was repeating same duplicate records.
//Below event is fetching top 8 rows on page load
function viewAllEvents() {
$.ajax({
url: "Event.aspx/viewEvents",
data: null,
contentType: "Application/json; charset=utf-8",
responseType: "json",
method: "POST",
success: function (response) {
var x = response.d;
for (var i = 0; i < x.length; i++) {
$("#tabss > .event-container > .row").append(
"<div class='col-md-3'><div class='event'><div class='eventsimg'><img src= " + '../MediaUploader/' + x[i].EVE_IMG_URL + " alt=''></div><div class='event-content'><h3 class='title'>" + x[i].EVE_NAME + "</h3><p>" + x[i].EVE_DESCRIPTION + "</p><input type='button' id=" + i + " class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;' onClick='eveReq(" + i + ", " + x[i].ID + ", " + x[i].EVE_CAT_ID + ");' value='Send Request' /><input type='button' class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;margin-left: 2px;' value='Read More' /></div><div class='links clearfix'></div></div></div>"
);
}
},
error: function (xhr) {
alert(xhr.status);
},
Failure: function (response) {
alert(response);
}
});
}
//Below event is for when load more button is clicked
function addTabs() {
$.ajax({
url: "Event.aspx/addTab",
data: null,
contentType: "Application/json; charset=utf-8",
responseType: "json",
method: "POST",
success: function (response) {
var x = response.d;
for (var i = 0; i < x.length; i++) {
$("#tabss > .event-container > .row").append(
"<div class='col-md-3'><div class='event'><div class='eventsimg'><img src= " + '../MediaUploader/' + x[i].EVE_IMG_URL + " alt=''></div><div class='event-content'><h3 class='title'>" + x[i].EVE_NAME + "</h3><p>" + x[i].EVE_DESCRIPTION + "</p><input type='button' id=" + i + " class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;' onClick='eveReq(" + i + ", " + x[i].ID + ", " + x[i].EVE_CAT_ID + ");' value='Send Request' /><input type='button' class='btn btn-pri' style='padding: 9px 9px;font-size: 12px;margin-left: 2px;' value='Read More' /></div><div class='links clearfix'></div></div></div>"
);
}
},
error: function (xhr) {
alert(xhr.status);
},
Failure: function (response) {
alert(response);
}
});
}
Below is my web methods:
[WebMethod]
public static List<EVENT> viewEvents()
{
var slist = new List<EVENT>();
var db = new BLUEPUMPKINEntities();
db.Configuration.LazyLoadingEnabled = false;
slist = db.EVENTS.OrderByDescending(eve => eve.ID).Take(8).ToList();
return slist;
}
[WebMethod]
public static List<EVENT> addTab()
{
var slist = new List<EVENT>();
var db = new BLUEPUMPKINEntities();
db.Configuration.LazyLoadingEnabled = false;
slist = db.EVENTS.OrderByDescending(eve => eve.ID).Skip(8).Distinct().ToList();
return slist;
}
Though I didn't use your code but I believe if you can go through this example below then you'll know what to do:
First declare a global variable which will count the record returned so far:
private int recordCount = 0;
Then in the click event do the following:
//My sample data
int[] data = { 1, 2, 3, 4, 5, 6, 7, 8 };
var results = data.Skip(recordCount).Take(2);
//Increment recordCount by the count of the results return above
recordCount+= results.Count();
if (results.Count() > 0)
{
//return results
}

Json result Not Binding to aspx?

I have a service and it is returning json in the following format
Data {
"TerminalID": 21,
"TerminalName": "NewTested",
"PortID": 27,
"PortName": "Badu Island",
"EffectiveStart": "2013-03-20T00:00:00",
"EffectiveEnd": "2013-03-23T00:00:00",
"ServiceID": 2
}
and in my aspx page my code is:
<script type="text/javascript">
$(document).ready(function () {
$("#divImageGo").click(function () {
var valId = 2;
$.ajax({
type: "GET",
url: "VoyageOneService.svc/BindVoyageDetails" + valId,
//data: '{"ServiceID":"2"}',
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
ServiceSucceeded(result);
},
error: function (msg) {
$("#errorDiv").text(msg);
}
});
});
});
And success does the following:
function ServiceSucceeded(data) {
alert("Success");
for (var i = 0; i < data.d.length; i++) {
$("#dlistVoyageDetails").append("<tr><td>" + data.d[i].TerminalName + "</td><td>" + data.d[i].PortName + "</td><td>" + data.d[i].EffectiveStart + "</td></tr>" + data.d[i].EffectiveEnd + "</td></tr>");
}
}
function ServiceFailed(xhr) {
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
In this ..,
Iam getting My service called
Iam getting my Return value of json
Iam getting the Success fired with its alert msg
But I am unable to get the result. When I checked my alert with the result I am getting NULL
Remove the if condition and it will work.
As data.length is null hence you condition is not satisfied.
function ServiceSucceeded(data) {
alert("Success");
$("#dlistVoyageDetails").append("<tr><td>" + data.d[i].TerminalName + "</td><td>" + data.d[i].PortName + "</td><td>" + data.d[i].EffectiveStart + "</td></tr>" + data.d[i].EffectiveEnd + "</td></tr>");
}

How to save Data In Database to the controller

How to save Data In Database to the controller.i am using jquery to get data from the textbox. please help me.
Contactcontroller.cs
public ActionResult Create(string Name, string Company, string
Regarding, string Email, string Phone, string Message) {
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
try
{
// code
}
catch
{
}
jquery.js
$("#btnSubmit").click(function (event) {
var data = { Name: $("#txtbxName").val(), Company: $("#txtbxCompany").val(), Regarding:
$("#ddlRegarding").val(), Email: $("#txtbxEmail").val(), Phone: $("#txtbxPhone").val(), Message:
$("#txtarMessage").val()
}
$.ajax({
type: "POST",
url: "/Contact/Create", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
dataType: "html",
success: function (result) {
$("#txtarMessage").val("");
alert(result);
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function (result) {
alert('Thanks for sending info');
location.reload();
return false;
}
});
});
i am getting data to the textbox using jquery.
now i want to save the whole data in the database through Controller.
Jquery
$.post('/Controller/Create', { Name: $('#Name').val(), Company: "Company", Regarding: "", Email: "",Phone: "",Message: ""}, function (data) {
});
Controller Action
public JsonResult Create(string Name, string Company, string Regarding, string Email, string Phone, string Message)
{
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
return Json(body, JsonRequestBehavior.AllowGet);
}

Categories

Resources