Autocomplete - two fields - javascript

I'm trying to create a page with fields, that use autocomplete function.
The first field - "ana" works fine. The second fails. I don't see any errors in the console. The prompt doesn't appear.
Here the snippet:
<script src="/inc/jquery-1.8.3.js"></script>
<script src="/inc/jquery-ui.js"></script>
<link href="/inc/jquery-ui.css" rel="stylesheet" type="text/css"/>
<table>
<tr>
<td>Ticker:</td><td><input type="text" name="ana" /></td>
</tr>
<tr>
<td>Cmp: </td><td><input type="text" name="sou" /></td>
</tr>
</table>
<div id="result" style="margin-top:25px;"></div>
<script language="javascript">
$(document).ready(function() {
ana = [ <% getAna %>];
$("input[name='ana']").autocomplete({ source: ana });
sou = [ <% getSou %>];
$("input[name='sou']").autocomplete({ source: sou});
});
</script>
I' cutting getAna and getSou. These works. Here the js/html source code:
<script language="javascript">
$(document).ready(function() {
ana = [ "Aar Edw"];
$("input[name='ana']").autocomplete({ source: ana });
sou = [ "A&A Equity Research"];
$("input[name='sou']").autocomplete({ source: sou});
});
</script>

try this
$(document).ready(function () {
var ana = Array();
$.ajax({
type: "POST",
url: "pagename.aspx/GetAna", //GetAna must be public static web method
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
$.map(data.d, function (item) {
ana.push(item.name);
})
}
});
$("input[name='ana']").autocomplete({ source: ana });
var sou = Array();
$.ajax({
type: "POST",
url: "pagename.aspx/GetSou", //GetSou must be public static web method
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
$.map(data.d, function (item) {
ana.push(item.name);
})
}
});
$("input[name='sou']").autocomplete({ source: sou });
});
in code behind
[WebMethod]
public static List<valuepair> GetAna()//example method same method for GetSou
{
List<valuepair> lstvaluepair = new List<valuepair>();
// ResumeFromBAL objResumeFromBAL = new ResumeFromBAL();
// ResumeFrom objResumeFrom = new ResumeFrom();
DataSet ds = new DataSet();//use your code to get dynamic data
// ds = objResumeFromBAL.GetANA();
if (ds.Tables.Count > 0)
{
foreach (DataRow item in ds.Tables[0].Rows)
{
lstvaluepair.Add(new valuepair() { name = item["ResumeFromName"].ToString(), value = item["ResumeFromId"].ToString() });
}
}
return lstvaluepair;
}
public class valuepair
{
public string name { get; set; }
public string value { get; set; }
}

Related

The json string I'm sending from javasript throught the function $.ajax() to my http controller funtion is null

SendData: function () {
var jasonStr = JSON.stringify(GamePlayedObj);
console.log(jasonStr);
$.ajax({
type: "POST",
async: false,
url: '#Url.Action("GamesSoFar", "AllCards")',
dataType: "json",
data: jasonStr,
contentType: "application/json; charset=utf-8"
});
}
[Route("Output")]
[HttpPost]
public ActionResult GamesSoFar(string jasonStr) {
string j = jasonStr;
string a = "";
GameInfo InfoOfTheLastGame = JsonConvert.DeserializeObject<GameInfo>(jasonStr);
_context.Add(InfoOfTheLastGame);
_context.SaveChanges();
var AllGames = _context.AllGames.Include(g => g.AllGames).ToList();
return View(AllGames);
}
I'm using the Asp.net core webApi. The parameter I use on my function controller goes null instead of the json string..the j and the a variables are for debbuging reasons any ideas?
Your code put the jasonStr into request body,so you cannot get the data in controller.If you want to get the jasonStr,you can use [FromBody] to specify that a parameter or property should be bound using the request body and use GameInfo jasonStr rather than string jasonStr to bind the data.
Here is a demo worked:
GameInfo:
public class GameInfo
{
public string name { get; set; }
public int price { get; set; }
}
View:
<div>
<button onclick="SendData()">SendData</button>
</div>
#section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
var GamePlayedObj = {};
GamePlayedObj.name = "game1";
GamePlayedObj.price = 10;
function SendData() {
var jasonStr = JSON.stringify(GamePlayedObj);
console.log(jasonStr);
$.ajax({
type: "POST",
async: false,
url: '#Url.Action("GamesSoFar", "AllCards")',
dataType: "json",
data: jasonStr,
contentType: "application/json; charset=utf-8"
});
}
</script>
}
Controller:
[Route("Output")]
[HttpPost]
public ActionResult GamesSoFar([FromBody]GameInfo jasonStr)
{
string a = "";
return View("OutPut");
}
Result:

jquery, Autocomplete URL call using ajax not working

I am using Jquery to implement autocomplete to my textbox, i have used Ajax call,but my ajax url is not working.
When i inspect it is showing this error -> POST http://localhost:51444/Searchoperation/searchvalues 404 (Not Found)
My HTML and Script code
<script>
$('#myInput').keyup(function (event)
{
var searchname = $('#myInput').val()
$('#myInput').autocomplete(
{
scroll: true,
selectFirst: false,
autoFocus: false,
source: function(request, response)
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Searchoperation/searchvalues",
data: "{'Searchname':'" + searchname + "'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
},
error: function (result) { }
});
},
select: function (event, ui) {
var vll = ui.item.val;
var sts = "no";
var url = 'search_app.aspx?prefix=' + searchname; // ur own conditions
$(location).attr('href', url);
}
})
})
</script>
<form autocomplete="off">
<div class="search-field" style="width:300px;">-->
<input id="myInput" type="text" name="myCountry" placeholder="SearchName" >
</div>
<input type="submit">
</form>
Code for fetching values from database
public List<string> searchvalues(string searchname)
{
try
{
List<string> result = new List<string>();
string connectionstring = #"Data Source=DESKTOP-LTV06QJ\SQLEXPRESS;Initial Catalog=Search;Integrated Security=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "connection_string";
conn.Open();
SqlCommand cmd = new SqlCommand("Sp_Search", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Emp_Name", searchname);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(string.Format("{0}/{1}", dr["Emp_id"], dr["Emp_Name"]));
}
conn.Close();
return result;
}
catch (Exception ex)
{
return null;
}
}
value entered in textbox is read but ajax call is not working.please help
try to use slash in the beginning of the path ("/Searchoperation/searchvalues"):
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Searchoperation/searchvalues",
data: "{'Searchname':'" + searchname + "'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('/')[0],
val: item.split('/')[1]
}
}));
},
....
You are missing page extension(.ASPX). Replace the ajax attribute URL like below,
url: "Searchoperation.aspx/searchvalues"
Also, make sure you have added [WebMethod] before the searchvalues method.
I hope this will help.

Jquery FormData can append array to upload on net core?

I writed this code to upload file using Jquery
and I ready a model to maaping this ajax return
$("input[name='ResolutionAttachedFile']")
.each(function () {
var ReadyToUpload = $(this)[0].files;
if (ReadyToUpload.length > 0) {
$.each(ReadyToUpload, function (i, file) {
data.append("ResolutionAttachedFile", file);
});
}
});
test.append('MyIFormFile', data);
jQuery.ajax({
url: '/Home/DocumentPage',
data: test,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
and this is my controller and data model
public class test
{
public testArea MyIFormFile { get; set; }
public class testArea
{
public List<IFormFile> ResolutionAttachedFile { get; set; }
}
}
[HttpPost]
public IActionResult DocumentPage(test _test)
{
return View();
}
but this model can't mapping value.
and I don't want to change model structure.
so how can I do let it can working?
For binding to MyIFormFile.ResolutionAttachedFile, you need to pass with MyIFormFile.ResolutionAttachedFile.
Make a test with ajax below:
<div>
<input type="file" multiple name="ResolutionAttachedFile" />
</div>
#section Scripts{
<script type="text/javascript">
$("input[name='ResolutionAttachedFile']")
.change(function () {
var data = new FormData();
$("input[name='ResolutionAttachedFile']").each(function () {
var ReadyToUpload = $(this)[0].files;
if (ReadyToUpload.length > 0) {
$.each(ReadyToUpload, function (i, file) {
data.append("MyIFormFile.ResolutionAttachedFile", file);
});
}
});
jQuery.ajax({
url: '/DocumentPage',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
});
</script>
}
Note
As my test, it will fail when the project is under netcoreapp2.1, it fail to bind when there is no extra properties in testArea. It only works when there is additionl properties like Name and set the name value from ajax.
For resolving this issue, you could migrate your project to netcoreapp2.2.
Here is my working .csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<UserSecretsId>aspnet-IdentityCore-85ED30A8-40E9-4BD5-A9D2-EAF6BCF0D5F1</UserSecretsId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0-preview3-35497" PrivateAssets="All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.5" PrivateAssets="All" />
</ItemGroup>
</Project>

How To Load json Data To PivotTable.js in Mvc

I am using PivotTable.js
Run-time error and I do not know what is
[HttpGet]
public JsonResult DataResult ()
{
List<jsonList> list = new List<jsonList>();
for (int i = 0; i < 100; i++)
{
jsonList New = new jsonList();
New.Age = i;
if (i % 2 == 0)
{
New.Gender = "Female";
}
else
{
New.Gender= "Male";
}
New.Name= i.ToString();
New.Party = "NDP";
New.Province= "Quebec";
list.Add(New);
}
return Json(list, JsonRequestBehavior.AllowGet);
}
and View
JavaScript code snippet at the bottom
<link href="../../assets/PivotCss/pivot.css" rel="stylesheet" />
<div id="output"></div>
<script src="~/scripts/Pivote/jquery-1.8.3.min.js"></script>
<script src="~/scripts/Pivote/jquery-ui-1.9.2.custom.min.js"></script>
<script src="~/scripts/Pivote/**pivot.js**"></script>
<div id="output"></div>
<script>
$(document).ready(function () {
jQuery.ajax({
type: "Get",
url: "/ReportBuilder/DataResult",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: [],
success: function (data) {
alert(JSON.stringify(data));
$("#output").pivot(
JSON.stringify(data),
{
rows: ["Age"],
cols: ["Province", "Party"]
}
);
}
});
});
</script>
And Alert Result Json
And Firebug Error page
This error is that when run
Thanks for your kindness

Auto complete in asp.net using jquery

Here I'm trying to use jquery auto complete in asp.net, I'm trying to retrieve the data from sql data source and use that for auto fetch. while I running the code auto complete have not worked.
my code
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Inventory.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtPartno').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
textbox field
<asp:TextBox ID="txtPartno" CssClass="Textboxbase" class="autosuggest" runat="server"></asp:TextBox>
and my c# code
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=MYPC-GN\\KASPLDB;Integrated Security=False;User ID=sa;Password=*****;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT PART_NO from Inventory where UserName LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
One problem which I can see is your javascript call is little wrong. You cannot get the value of textbox which is created by asp itself with document.getElementById('txtPartNo'). To get this value, you will have to get it's client id which you can get using-
txtPartNo.ClientID so finally this will become-
data: "{'username':'" + document.getElementById('<%= txtPartno.ClientID %>').value + "'}",
If you don't try this way then you will not get the actual value of that textbox and undefined will be sent to the C# method which will not return anything.
First you should check if the JavaScript function it's getting called.
If it's getting called then you should check if the url is correct.
You can check in developer tools/ firebug etc. to see what request are you sending.
I did as follows:
ajaxCallSetting.js
var ajaxCallSetting = function (element, message, req) {
var baseInfo = {
baseUrl: "http://localhost:10266/"
};
var buildUrl= function() {
return baseInfo.baseUrl + message;
};
var callApi = function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: buildUrl(),
data: JSON.stringify(req),
dataType: "json"
}).success(function(data) {
response(data.d);
});
};
return {
init: function() {
$(element).autocomplete({
source: callApi
});
}
};
};
The head tag:
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
<script src="ajaxCallSetting.js"></script>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" />
<script type="text/javascript">
$(document).ready(function () {
var req = {
username: $('#txtPartno').val()
};
apiSettings('#txtPartno', "Default.aspx/GetAutoCompleteData", req).init();
});
</script>
</head>
As far as possible,
Keeping separate Html code with the code in JavaScript is useful.
I don't think your TextBox is being hooked up properly. Try this:
<asp:TextBox ID="txtPartno" CssClass="Textboxbase autosuggest" runat="server"></asp:TextBox>
And try this in your JavaScript:
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Inventory.aspx/GetAutoCompleteData",
data: "{'username':'" + request.term + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});

Categories