Uncaught Error in autocomplete select item - javascript

I am getting autocomplete item list from javascript autocomplete but when I select that autocomplete item list at that time it shows the error i.e. Uncaught TypeError: n.item is undefined
Here is my code,
<div class="form-group">
<div class="col-md-3">
<nop-label asp-for="Name" />
</div>
<div class="col-md-9">
#Html.TextBoxFor(model => Model.Name, new { #class = "form-control" })
#Html.HiddenFor(model => Model.Name)
</div>
</div>
$(document).ready(function () {
$("#Name").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("AutoComplete", "Product")',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val) {
return {
label: val.Name,
value: val.Name
}
}))
}
})
},
select: function (ui) {
$("#Name").val(ui.item.Name);
}
});
});
Here is the controller
public JsonResult AutoComplete(string term = "")
{
var objCustomerlist = (from product in _productMasterRepository.Table
where product.Name.StartsWith(term)
select new
{
Name = product.Name,
ID = product.Name
}).ToList();
return Json(objCustomerlist);
}

Your select signature is incorrect:
select: function (ui) {
$("#Name").val(ui.item.Name);
}
Change it into:
select: function (event, ui) {
$("#Name").val(ui.item.Name);
}
And that should work fine.

Related

Select section showing undefined in ajax autocomplete

I getting name perfectly but I am not getting their name related ID in ajax autocomplete
Following is the view code,
#Html.TextBoxFor(model => Model.CustomerFullName, new { #class = "form-control" })
#Html.TextAreaFor(model => Model.CustomerId)
$(document).ready(function () {
$("#CustomerFullName").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("AutoComplete", "Order")',
datatype: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val) {
return {
value: val.Name,
label: val.Name
}
}))
}
})
},
select: function (event, ui) {
alert(ui.item.id);
$("#CustomerId").val(ui.item.id);
}
});
});
Here is the controller,
public JsonResult AutoComplete(string term = "")
{
var objCustomerlist = (from customer in _customerRepository.Table
where customer.Username.StartsWith(term)
select new
{
Name = customer.Username,
ID = customer.Id
}).ToList();
return Json(objCustomerlist);
}
In autocomplete ajax select section alert showing undefined
I tried things to solve like
JSON.Stringfy(ui.item.id)
ui.id
but still didnt work.

How can I serialize a form in JavaScript asp.net

I am using some javascript to post my form but I dont want to have to submit each form field is there a way I can serlize this to an object in .net so that it will bring in all the form contents.
section Scripts {
<script>
function confirmEdit() {
swal({
title: "MIS",
text: "Case Created your Case Number is " + $("#Id").val(),
icon: "warning",
buttons: true,
dangerMode: true,
}).then((willUpdate) => {
if (willUpdate) {
$.ajax({
url: "/tests/edit/" + $("#Id").val(),
type: "POST",
data: {
Id: $("#Id").val(),
Name: $("#Name").val()
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully edited!", "success")
.then((success) => {
window.location.href = "/tests/index"
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error updating!", "Please try again", "error");
}
});
}
});
}
</script>
}
asp.net core will automatically bind json data using the [FromBody] attribute.
data: {
id: $("#Id").val(),
name: $("#Name").val()
},
and then in your controller
[HttpPost("/tests/edit/")]
public IActionResult Process([FromBody] MyData data){ ... }
where MyData is
public class MyData
{
public string Id {get;set;}
public string Name {get;set;}
}
section Scripts { function confirmEdit() {
swal({ title: "MIS", text: "Case Created your Case Number is " + $("#Id").val(), icon: "warning", buttons: true, dangerMode: true, }).then((willUpdate) => { if (willUpdate) {
var obj = { Id: $("#Id").val(), Name: $("#Name").val() }
$.ajax({ url: "/tests/edit/" + $("#Id").val(), type: "POST", data: JSON.Stringify(obj), dataType: "html", success: function () { swal("Done!", "It was succesfully edited!", "success") .then((success) => { window.location.href = "/tests/index" }); }, error: function (xhr, ajaxOptions, thrownError) { swal("Error updating!", "Please try again", "error"); } }); } }); } }
in c# use
public ActionResult FormPost(MyData obj)
Please refer to the following methods to submit the form data to action method:
using the serialize() method to serialize the controls within the form.
#model MVCSample.Models.OrderViewModel
<h4>OrderViewModel</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Showsummary" asp-controller="Home" method="post" class="signup-form">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="OrderId" class="control-label"></label>
<input asp-for="OrderId" class="form-control" />
<span asp-validation-for="OrderId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="OrderName" class="control-label"></label>
<input asp-for="OrderName" class="form-control" />
<span asp-validation-for="OrderName" class="text-danger"></span>
</div>
<div id="packages">
#for (int i = 0; i < Model.Packages.Count; i++)
{
<div class="form-group">
<label asp-for="#Model.Packages[i].Pid" class="control-label"></label>
<input asp-for="#Model.Packages[i].Pid" class="form-control" />
<span asp-validation-for="#Model.Packages[i].Pid" class="text-danger"></span>
<br />
<label asp-for="#Model.Packages[i].PackageTitle" class="control-label"></label>
<input asp-for="#Model.Packages[i].PackageTitle" class="form-control" />
<span asp-validation-for="#Model.Packages[i].PackageTitle" class="text-danger"></span>
</div>
}
</div>
</form>
</div>
</div>
<div>
<input type="button" id="summary" value="Summary" />
<div id="page_3">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: $("form.signup-form").serialize(),
success: function (data) {
console.log(data)
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
</script>
Code the the action method:
[HttpPost]
public PartialViewResult Showsummary(OrderViewModel model)
{
try
{
//...
return PartialView("OrderSummary", model);
}
catch
{
return PartialView("OrderSummary", model);
}
}
After clicking the button, the result like this:
As we can see that, we could get the element's value in the form and even the nested entity.
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Create a JavaScript object, and post it to action method.
Change the JavaScript script as below:
$(function () {
$("#summary").click(function () {
console.log("calling summary");
event.preventDefault();
//create a object to store the entered value.
var OrderViewModel = {};
//using jquery to get the entered value.
OrderViewModel.OrderId = $("input[name='OrderId']").val();
OrderViewModel.OrderName = $("input[name='OrderName']").val();
var packages = [];
//var count = $("#packages>.form-group").length; //you could use it to check the package count
$("#packages>.form-group").each(function (index, item) {
var package = {}
package.Pid = $(item).find("input[name='Packages[" + index + "].Pid']").val();
package.PackageTitle = $(item).find("input[name='Packages[" + index + "].PackageTitle']").val();
packages.push(package);
});
//add the nested entity
OrderViewModel.Packages = packages;
$.ajax({
type: "POST",
url: "/Home/Showsummary", //remember change the controller to your owns.
data: OrderViewModel,
success: function (data) {
console.log(data)
$('#page_3').html(data);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});
});
});
By using the above code, I could also get the submit entity, you could refer to it.

asp.net mvc 4 - linq Contains operator is working as if it were a StartsWith operator

controller:
[HttpPost]
public JsonResult Index(string search)
{
var data = LoadExplore_SP("sp_View_Explore");
List<ExploreModel> stuff = new List<ExploreModel>();
foreach (var row in data)
{
stuff.Add(new ExploreModel
{
Thing_Title = row.Thing_Title
});
}
//Searching records from list using LINQ query
var ThingList = (from N in stuff
where N.Thing_Title.Contains(search)
select new { N.Thing_Title });
return Json(ThingList, JsonRequestBehavior.AllowGet);
}
view:
<script type="text/javascript">
$(document).ready(function () {
$("#Thing_Title").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Index",
type: "POST",
dataType: "json",
data: { search: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Thing_Title, value: item.Thing_Title };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.Thing_Title, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
</div>
}
My problem is that I can't get the linq where clause to work the way it should. Instead of returning results like %search%, it is returning all records like 'search%' instead.
Do you know why it's behaving this way?

Autocomplete does not appear in view, ASP.NET MVC

I have one field in my view, it is a textbox field. But I'd like to change that field to an Autocomplete dropdown.
Below is my view:
#Html.TextBoxFor(model => model.SearchFilterPaymentCode, new { #class = "form-control", #id = "searchInput1" })
#Html.HiddenFor(model => model.ID)
<script>
$(document).ready(function () {
$("#searchInput1").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("getJenisPembayaran", "Payment1")',
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response($.map(data, function (val, item) {
return {
label: val.Name,
value: val.Name,
ID: val.ID
}
}))
}
})
},
select: function (event, ui) {
$("#ID").val(ui.item.ID);
$("#SearchFilterPaymentCode").val(ui.item.label);
}
});
})
</script>
and below is my controller
public JsonResult getJenisPembayaran(string term)
{
var objCustomerlist = db.ParamJenisPembayarans.Where(x => x.Name.ToUpper()
.Contains(term.ToUpper()))
.Select(x => new ParamJenisPembayaranViewModel
{
ID = x.ID,
JenisPembayaran = x.Name
}).Distinct().ToList();
return Json(objCustomerlist, JsonRequestBehavior.AllowGet);
}
When I debug the controller and fill the textbox with a few words, I get some data from the database, that means the controller is working well but the data does not appear in the view. What's wrong with my code?

Autocomplete Textbox from database MVC 5

I have my textboxfor field which select the data from role table from the database
i need this textboxfor field make a autocomplete with starting character.
Sample:
MVC code:
This JsonResult in the UsersControl
public JsonResult GetRoles(string Prefix)
{
var RoleListVal = db.Roles.Where(r => r.Deleted == false)
.Where(r => r.Name.ToUpper().StartsWith(Prefix))
.Select(r => new { Name = r.Name, ID = r.RoleID }).Distinct().ToList();
return Json(RoleListVal, JsonRequestBehavior.AllowGet);
}
cshtml Code:
This the JS and the HTML5 TextBoxFor:
$("#keywords-manual").autocomplete({
source: "/Users/GetRoles",
minLength: 1
})
<div class="form-inline">
#Html.Label("Role :")
#Html.TextBoxFor(model => model.Roles.FirstOrDefault().Name, new { #class = "form-control", #id = "keywords-manual" })
</div>
I don't why isn't working!
Here your controller side method looks good.
But issue is while you calling method.
$("#keywords-manual").autocomplete({
source: function (request, response) {
$.ajax(
{
type: "POST",
url: '#Url.Action("GetRoles","Users")',
data: { Prefix: $('#keywords-manual').val() },
dataType: "json",
success: function (data) {
response($.map(data, function (item) {
return {
value: item.Name,
description: item
}
}))
},
error: function (error) {
console.log(error);
}
});
},
minLength: 1,
select: function (event, ui) {
}
});
This is how you configure the Autocomplete plug in
On HTML Side:
$(function () {
$("#keywords-manual").autocomplete({
source: "#Url.Action("GetRoles","Users")",
minLength: 1
})
});
On the controller side:
public JsonResult GetRoles(string term)
{
var RoleListVal = db.Roles.Where(r => r.Deleted == false)
.Where(r => r.Name.ToUpper().StartsWith(term))
.Select(r => new { label = r.Name, id = r.RoleID,value=r.RoleID }).Distinct().ToList();
return Json(RoleListVal, JsonRequestBehavior.AllowGet);
}

Categories