Post request doesn't receive data from autocomplete (jQuery) - javascript

I apaologize in advance if not enough info will be given, I'm just a novice, but i will try to explain it the best I can.
In short, the data from ajax is not sent back to the "AutoComplete" request in the controller. I have a input form field that is directly connected to the autocomplete function, the "url" is specified and all the components i can think of. I think the problem is in the "data" part of the code, but I'm not quite sure. When i hardcode the incoming string value to a letter that one of the names in my database contains, then it works fine (discluding the possibility of the controller not working properly). Code below.
Home controller
[HttpGet]
public IActionResult TestView()
{
return View();
}
[HttpPost]
public JsonResult AutoComplete(string prefix)
{
var customers = (from customer in _context.Customers where customer.Name.StartsWith(prefix) select new {
label = customer.Name, val = customer.CustomerId})
.ToList();
return Json(customers);
}
[HttpPost]
public IActionResult TestView(string CustomerName, string CustomerId)
{
ViewBag.Message = "CustomerName: " + CustomerName + " CustomerId: " + CustomerId;
return View();
}
TestView.cshtml
<body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" />
<script>
$(function() {
$("#txtCustomer").autocomplete({
source: function(request, response) {
$.ajax({
url: '/Home/AutoComplete/',
data: "{ 'prefix': '" + request.term + "'}", #* also tryed == > data: { prefix: request.term }*#
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data, function(item) {
return item;
}))
},
error: function(response) {
alert(response.responseText);
},
failure: function(response) {
alert(response.responseText);
}
});
},
select: function(e, i) {
$("#hfCustomer").val(i.item.val);
},
minLength: 1
});
});
</script>
#using (Html.BeginForm("TestView", "Home", FormMethod.Post))
{
<input type="text" id="txtCustomer" name="CustomerName"/>
<input type="hidden" id="hfCustomer" name="CustomerId" />
<br />
<br />
<input type="submit" id="btnSubmit" value="Submit" />
<br />
<br />
#ViewBag.Message
}
</body>
Hope I managed to explain enough and sorry if my terminology is not the best. Thank you!

Related

Passing multiple type of data via AJAX to MVC C# Controller

I'm using AJAX to get the info from the Razor View and send it to controller
Everything is working but now I need to pass an Array + String so the data could be:
// View - Javascript
var idkey = $('#idkey').val();
var selected = ['test1', 'test2', 'test3'];
$.ajax({
type: 'POST',
url: '/Adm/MyAction',
traditional: true,
data: { idkey: idkey, selected: selected }), ...
// Controller
[HttpPost]
public async Task<JsonResult> MyAction(string idkey, string[] selected)
{
// Do something with the data passed on params
}
The issue is ... I can't find anywhere how to send two different types of data from AJAX to controller
this works:
Controller:
public class HomeController : Controller
{
[HttpPost]
public string Index900(string theValue, string[] stringArray)
{
//put breakpoint here
try
{
throw new Exception("this is the Value" + theValue);
}
catch (Exception ex)
{
return ex.Message;
}
}
public ActionResult Index()
{
return View();
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script>
$(function () {
$("#theBtn").click(function () {
var idkey = $('#idkey').val();
var selected = ['test1', 'test2', 'test3'];
var theValue = $("#theInput").val();
$.ajax({
url: "/Home/Index900",
dataType: 'text',
type: 'post',
contentType: 'application/json',
data: JSON.stringify({ theValue: idkey, stringArray: selected }),
success: function (result) {
alert(result);
},
error: function (data) {
alert("error...")
}
});
});
});
</script>
</head>
<body>
<div>
<input type="button" id="theBtn" value="Click to start ajax" />
<input type="text" id="idkey" value="Some Value" />
</div>
</body>
</html>

Javascript autocomplete not working in ascx

I have a autocomplete in a grid-view in a ascx file but the autocomplete is not working in the ascx file. I have made several similar autocomplete in other page that work. Why is it that the autocomplete does not work in my ascx file. I have a hypotheses why it does not work but I am unsure how to fix it here it is
I think that the problem is with the following url in the javascript
url: "contratoGerencia.aspx/getSupplierAndComponente"
However I dont know how I should change it don get it to work with the ascx file.Also I found a solution here https://www.codeproject.com/Questions/757769/How-to-Call-Ascx-page-form-JavaScript-Funnction-Of that is almost what I want the only problem is that I also have a textbox in my situation.
Any help would be very appreciated. I hope the following information will help you.
Here is my ascx (ComponentesControler.ascx) code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<link href="../css/autocomplete.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript" src="../scripts/autocomplete.js" ></script>
<asp:TextBox CssClass="gridContractAndComponente" ID="txtContractComponenteFooter" Text="" runat="server" TextMode="MultiLine" Rows="1" />
Here is my ascx.cs (ComponentesControler.ascx.cs) code
[WebMethod]
public static List<string> getSupplierAndComponente(string prefixText)
{
string lv_numero_contrato;
List<string> numeros_contrato = new List<string>();
connectionStringBuilder builder = new connectionStringBuilder();
String connString;
connString = builder.builder.ConnectionString;
string selectStatement = " SELECT numero_contrato FROM erp_contratos ";
using (MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(connString))
{
conn.Open();
using (MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = selectStatement;
cmd.Parameters.AddWithValue("#searchText", prefixText);
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
lv_numero_contrato = reader.GetString(reader.GetOrdinal("numero_contrato"));
numeros_contrato.Add(lv_numero_contrato);
}
}
conn.Close();
}
}
return numeros_contrato;
}
Here is the aspx page (contratoGerencia.aspx) were I use the ascx file
<div id="ComponentesSection" class="menusection">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Always" >
<ContentTemplate>
<TWebControl5:WebControl5 ID="Header8" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
Here is my javascript file (autocomplete.js)
$(document).ready(function () {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
The problem is in the name of your parameter entered in AJAX, your method expects to receive a parameter named prefixText and not containedText.
Change
data: {'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
with
data: {'prefixText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}
The issue can be triggered by the UpdatePanel like explained here:
jQuery $(document).ready and UpdatePanels?
So modify your autocomplete.js like this:
$(document).ready(function() {
SearchSupplierAndComponente();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
SearchSupplierAndComponente();
});
function SearchSupplierAndComponente() {
$(".gridContractAndComponente").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "contratoGerencia.aspx/getSupplierAndComponente",
data: "{'containedText':'" + document.getElementById('PageContent_gvPrimaryGrid_txtContractComponenteFooter').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
See if the console error goes away.

Asp .net ajax autocomplete not working. Webmethod is not getting called

Can somebody tell me why WebMethod is not firing in one page alone, this same code works in another page, but not in the page which i want it to work. I shifted this entire code into a new page and it works perfectly fine there, but if i use it in my actual page, it doesn't fire the webmethod. Not sure what's happening.
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("[id$=txtSkill]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<% =ResolveUrl("HRMCareerEAF.aspx/GetSkills") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfSkillID]").val(i.item.val);
},
minLength: 1
});
});
</script>
<asp:TextBox ID="txtSkill" runat="server" style="text-align: center" />
[WebMethod(EnableSession = true)]
public static string[] GetSkills(string prefix)
{
HRMRecruitmentProcessDAL obj = new HRMRecruitmentProcessDAL();
DataSet ds = obj.BindMstcommon(HttpContext.Current.Session["CandidateID"].ToString(), "GetSkillsDD", "%" + prefix + "%");
List<string> skills = new List<string>();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
skills.Add(string.Format("{0}-{1}", ds.Tables[0].Rows[i]["Skill_Desc"].ToString(), ds.Tables[0].Rows[i]["skill_id"].ToString() + "|" + ds.Tables[0].Rows[i]["Skill_GroupID"].ToString())); //ds.Tables[0].Rows[i]["Skill_GroupDesc"].ToString() + " : " +
}
return skills.ToArray();
}
Can you please check few things
1) check if you are able to call the api using rest api testing tools like postman
2) If you are able to access it can you please check if web developer tool console if it has any error like 404(Not found) or 500(Internal server error)
3) Modify your
data: "{ 'prefix': '" + request.term + "'}",
to
data: JSON.stringify({ prefix: request.term }),
Please check value of '<% =ResolveUrl("HRMCareerEAF.aspx/GetSkills") %>'
Also I am not sure but try getting rid of (EnableSession = true).
Thank you soo much for the support.
I found out the problem and solution.
Actual problem is that auto complete doesn't work after partial page postback and my txtskill is in 3rd view of asp:multiview which refreshes only the part of page inside my updatepanel.
Jquery methods do not bind if the page postbacks partially. I got solution in the following link.
Jquery Auto complete extender not working after postback
My altered code is as follows.
<script type="text/javascript">
$(function () {
SetAutoComplete();
});
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
// Place here the first init of the autocomplete
SetAutoComplete();
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel re-init the Autocomplete
SetAutoComplete();
}
function SetAutoComplete() {
$("[id$=txtSkill]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<% =ResolveUrl("HRMCareerEAF.aspx/GetSkills") %>',
data: JSON.stringify({ prefix: request.term }),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
};
}))
}
});
},
select: function (e, i) {
$("[id$=hfSkillID]").val(i.item.val);
},
minLength: 1
});
}
</script>
Thank yo soo much for the support.

Postback event on text changed event

I want to postback on every keypress/textchanged event in textbox but my javascript is not running. Am i missing something...????
My Html textbox is this:
<asp:TextBox ID="Txt_Search" runat="server" AutoCompleteType="Disabled"
onkeypress="Postback();" OnTextChanged="Txt_Search_TextChanged" AutoPostBack="true">
</asp:TextBox>
My Javascript code is this:
function Postback() {
__doPostBack('<%= Txt_Search.ClientID %>', '');
};
My on textchanged event is this:
protected void Txt_Search_TextChanged(object sender, EventArgs e)
{
FolderStructure.Nodes.Clear();
Searchtxt();
}
I create sample projects ASP.NET WebForms and AJAX.
I Suggest you can use AJAX process .NET Generic Handler File. Please you research about Generic Handler file.
Before create Generic Handler file "Search.ashx" and Paste above the code.
public void ProcessRequest(HttpContext context)
{
var search = HttpContext.Current.Request.Form["term"];
//Dummy Data
List<string> searchList = new List<string> { "Red", "Orange", "Ping", "Blue", "White", "Black" };
string result = string.Empty;
if (!string.IsNullOrEmpty(search))
{
searchList = searchList.Where(x => x.ToLower().Contains(search.ToLower())).ToList();
if (searchList != null && searchList.Count() > 0)
{
foreach (var item in searchList)
{
result += "<li>" + item + "</li>";
}
}
}
else
{
result="<li> Not Found </li>";
}
context.Response.ContentType = "text/plain";
context.Response.Write(result);
}
public bool IsReusable
{
get
{
return false;
}
}
and Create Your Search Page, YourFile.aspx, my file name Search.aspx.
ASPX Page Code :
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication7.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtSearch" class="js-search" value="Search" />
<div class="searchResult">
<ul>
</ul>
</div>
</div>
</form>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>
<script>
$(function () {
$(".js-search").on('keyup', function () {
var term = $('.js-search').val();
if (term.length > 2) {
sendSearchRequest({ "term": term });
}
});
function sendSearchRequest(value) {
var datas = $.ajax({
type: "POST",
url: '/Search.ashx',
cache: false,
async: false,
data: value,
success: function (term) {
$('.searchResult').empty();
$('.searchResult').append(term);
}
});
}
});
</script>
</body>
</html>
This example when all three letters entered send ajax request search.ashx file and contains search term and get result on search page.
I hope that helps.
Modify code as below and check
__doPostBack('Txt_Search', '');
here is demo for dynamic search in asp.net.
Your textbox should be:
<asp:TextBox ID="PopertyName" placeholder="Property Name" href="#"
propertyid="" runat="server" class="dropdownAnchor"
autocomplete="off" onkeydown="SearchProperty()"></asp:TextBox>
here we will call a function named searchProperty() onkeydown event.
so, your ajax should be,
function SearchProperty() {
$.ajax({
url: '<%=Page.ResolveUrl("~/Dashboard/NewDashboard.aspx/GetProperty") %>',
data: "{ 'prefix': '" + $("#PopertyName").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//Your code to bind result that received from your back end.
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
};
these function will call a GetPoprty() method on newDashboard.aspx.cs file.
so my back end method is,
[WebMethod]
public static List<Model.Property> GetProperty(string prefix)
{
// Here you get your text in prefix
}

Viewmodel contents null after ajax call?

I am creating an ASP.NET MVC application. I am currently developing a search page where both the search box and the table of results are displayed on the same page. To do this I have used Partial Views and AJAX/JSON calls with a viewmodel. After entering the two search terms in the textbox, both are null in the controller after being passed through ajax.
Here is the code:
ViewModel:
public class ExampleViewModel
{
public string search { get; set; }
public string search2 { get; set; }
}
Controller:
[HttpPost]
public ActionResult Search(ExampleViewModel searchTerm)
{
var searchList = db.UserLists.Where(x => x.LastName.Contains(searchTerm.search));
return PartialView("_SearchResultsPartial", searchList);
}
Body of Index View:
<body>
<div>
#Html.TextBoxFor(model => model.search)
#Html.TextBoxFor(model => model.search2)
<input type="submit" value="Search" onclick="return getSearchResults()"/>
</div>
<div id="search-results">
</div>
<script>
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
function getSearchResults() {
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
</script>
Again, after setting a breakpoint on the Search [POST] method, the ExampleViewModel's terms are null.
At first sight, it seems that you have to retrieve the values within the function scope:
function getSearchResults() {
//Read these values on button click
var exViewModel = {
search: $('#search').val(),
search2: $('#search2').val()
}
$.ajax({
type: "POST",
data: JSON.stringify(exViewModel),
dataType: "json",
contentType: "application/json",
url : "/View/Search/",
success: function (result) {
$("#search-results").html(result);
}
});
}
Otherwise, the exViewModel is just determined on page load.

Categories

Resources