I am using Jquery with Ajax AutoComplete to return some data, but I'm kind of stuck with the display text.
This is what I have:
<script type="text/javascript">
$(document).ready(function () {
$("#locais").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("CreateF")',
datatype: "json",
data: {
s_localidade: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.remetente,
value: item.ID,
}
}))
}
})
},
});
});
And on controller:
public JsonResult CreateF(string s_localidade)
{
var tblOficiosExpedidos = db.tblOficiosExpedidos.Include(t => t.tblLocalidades);
var local = (from r in db.tblLocalidades
where r.Remetente.Contains(s_localidade.ToUpper())
select new { remetente = r.Remetente + " - " + r.Cidade, ID = r.LocalidadeID }).ToList();
return Json(local, JsonRequestBehavior.AllowGet);
}
On View:
#Html.TextBox("LocalidadeID","", htmlAttributes: new { #class = "form-control", #id="locais"})
It does work, but when i select an item, the text of the text box becomes the key number from my table. Is there a way to when i select something, the text keep as item.remetente but saves the number of item.ID into table?
You can do with the help of 'select'
try below approach
Your view
#Html.TextBox("LocalidadeID","", htmlAttributes: new { #class = "form-control", #id="locais"})
#Html.Hidden("hiddenlocais")
In your jquery define common function that takes both hidden and text box id as parameters
JQuery:
function WireUpAutoComplete(displayControlId, valueControlId)
{
$(displayControlId).autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("CreateF")',
datatype: "json",
data: {
s_localidade: request.term
},
select: function (event, ui) {
$(displayControlId).val(ui.item.Remetente);
$(valueControlId).val(ui.item.ID);
return false;
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.remetente,
value: item.ID,
}
}))
}
})
},
});
}
In document ready call above function
<script type="text/javascript">
$(document).ready(function () {
WireUpAutoComplete("#locais", "#hiddenlocais");
});
</script>
hope this solve your problem. i haven't tested. let me know if you face any problems
Related
I want to update a select list when the user selects a value in another select list. I've managed to get the first select list to call a get (or post) method on the model with a parameter, and can update the underlying data. But the second select list never shows the new values.
I'm not very experienced with asp.net, so what am I doing wrong?
Code below
.cshtml
<div>
<form method="post">
<select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
<select id="destinationStation" asp-items="Model.DestinationStations"></select>
</form>
</div>
#section Scripts {
<script type="text/javascript">
function getDestinationStations() {
var selectedDepartureStationID = $("#departureStation").find(":selected").val();
console.log("selectedDepartureStationID = " + selectedDepartureStationID);
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
console.log("success - " + result);
},
error: function() {
console.log("failure");
}
})
}
</script>
}
.cs
public List<SelectListItem> DestinationStations
{
get
{
if (this._selectedDepartureStationID == -1)
return new List<SelectListItem>();
List<Models.Station> stations = new List<Models.Station>();
List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
{
List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
stations.AddRange(routeSegments2.Select(x => x.Station));
}
return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
}
}
public IndexModel(MyViewContext context)
{
this._context = context;
}
public void OnGet()
{
this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
}
public IActionResult OnGetDeparture(int selectedDepartureStationID)
{
this._selectedDepartureStationID = selectedDepartureStationID;
return Page();
}
Whenever your #departureStation select changes, your code will call getDestinationStations javascript code. Inside that function you are sending a request to your backend server to receive possible destination stations if I understood correctly. What you need to do here is when ajax request successes, add options dynamically based on your returned array or data.
I am assuming your "/Index?handler=Departure" returns a JSON like:
[
{
id: 1,
name: "station1"
},
{
id: 2,
name: "station2"
}
]
Check if code below works.
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
let destinationStationSelect = $('#destinationStationSelect');
let optionTemplate = $('<option></option>');
$.each(result, (index, element) => {
let option = optionTemplate.clone();
option.append(element.name);
option.attr('value', element.id);
destinationStationSelect.append(option);
});
},
error: function() {
console.log("failure");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I'm working on a .NET Core 3.1 razor pages project, and, on one of my pages, I have an AJAX call on submitting the form details. On clicking the button, I am hitting the post handler and ModelState is valid, but the post is not redirecting to the desired page. I have tried to debug the AJAX call using the devtools and my success and failure functions are not being hit.
Where am I going wrong?
Javascript
$.ajax({
url: "/Candidate/Add?handler=Candidate",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(candidate),
success: function (data) {
//alert('success');
var t = data;
},
failure: function (data) {
var f = data;
}
})
Post handler
public async Task<IActionResult> OnPostCandidateAsync([FromBody] CandidateModel candidate)
{
if (!ModelState.IsValid)
{
IdTypeOptions = idTypeRepository.GetIDTypes().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
industryOptions = industryRepository.GetIndustries().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
GenderOptions = genderRepository.GetGender().Result.Select(g => new SelectListItem
{
Value = g.Id.ToString(),
Text = g.Name
}).ToList();
return Page();
}
//candidateModel.UserId =
var id = await candidateRepository.AddCandidate(candidate);
//return ()
return RedirectToPage("./Index");
}
Any help will be appreciated
ajax call always return some data, or partial view but never redirects inside of the action.
you have to fix on success of ajax
.....
data: ....,
success: function (data) {
window.location.href ...
//or
window.open(....)
},
error: function (jqXHR, exception) {
...error code
}
});
if you want to open another page use
window.location.href = 'http://...;' //the full url of razor page
if you want to open page in another window
window.open('the full url of razor page');
i had to return JsonResult on my post handler and passed the url i wanted to redirect to
public async Task<IActionResult> OnPostCandidateAsync([FromBody] CandidateModel candidate)
{
if (!ModelState.IsValid)
{
IdTypeOptions = idTypeRepository.GetIDTypes().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
industryOptions = industryRepository.GetIndustries().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
GenderOptions = genderRepository.GetGender().Result.Select(g => new SelectListItem
{
Value = g.Id.ToString(),
Text = g.Name
}).ToList();
return Page();
}
//candidateModel.UserId =
var id = await candidateRepository.AddCandidate(candidate);
return new JsonResult("/Candidate/Index");
//return ()
//return RedirectToPage("./Index");
}
and added the window.location.href on to the success function of the ajax call
$.ajax({
url: "/Candidate/Add?handler=Candidate",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(candidate),
success: function (data) {
window.location.href = data;
},
failure: function (data) {
var f = data;
}
})
#Serge thank you for your assistance
I'm a fairly new to JQuery, Json, and MVC. I am trying to a get the autocomplete to work in a text-box (with a drop-down). This is for a parameter value selection used in a web report. The data-table values are in the model called 'BSNList'. THen in the .cshtml View, the BSN text values have to be put to a var for the jquery function to run the autocomplete - I have it working with a inline list to test the autocomplete. But, I can't get the BSNList values to work in the jquery script- even trying with a JsonConvert.SerializeObject here is my code
birthCertificateModel.BSNList = new SelectList(_jobsParamData.AsDataView(), "JobId", "BSN");
birthCertificateModel.JSONresult = JsonConvert.SerializeObject(_jobsParamData);
return View(birthCertificateModel);
<div class="col-md-2">
#*<div class="ui-widget">*#
<label for="tags">BSNs: </label>
<input id="tags" class="ui-autocomplete-input" name="tags">
#*</div>*#
#Html.LabelFor(m => m.BSNName, ReportCaptions.BSN) <br />
#Html.ListBoxFor(m => m.BSNName,
Model.BSNList,
new { #class = "ListBox", size = 8 })
</div>
<script type="text/javascript">
var jsonBSNList;
jsonBSNList = #Model.BSNList.DataTextField;
$(document).ready(function () {
$(function () {
$("#tags").autocomplete({
source: jsonBSNList
});
});
});
`
Figured this out - here is my controller , html and script - I think the ajax is where I stumbled first.
[HttpPost]
public JsonResult SerialNumberLookup(string serialNumberString)
{
using (SqlConnection conn = new SqlConnection(this.connstr))
{
List<string> serialNumberList = new List<string>();
using (SqlCommand cmd =
new SqlCommand(BuildJobStatusModel.LookupSQLSelect, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#SearchText", serialNumberString);
SqlDataReader sqlDataReader = cmd.ExecuteReader();
while (sqlDataReader.Read())
{
serialNumberList.Add(sqlDataReader["SerialNumber"].ToString());
}
return this.Json(serialNumberList, JsonRequestBehavior.AllowGet);
}
}
<br />
#Html.LabelFor(model => model.SelectedSerialNumber, ReportCaptions.SerialNumber + " Look-up:")
#Html.TextBoxFor(model => model.SelectedSerialNumber, htmlAttributes: new { #id = "autocompleteSerialNumber" })
<br />
$("#autocompleteSerialNumber").autocomplete(
{
minLength: minSearchLen,
source: function (request, response) {
$.ajax({
url: "/Reports/SerialNumberLookup",
type: "POST",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data: { SerialNumberString: request.term },
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
value: item
};
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
})
}
});
I am trying to achieve autocomplete textbox functionality from database, it is not working. i have tried below code.
$(document).ready(function () {
$("#Manufacturer").autocomplete({
source: function (request, response) {
debugger
$.ajax({
url: '#Url.Action("GetRecord", "Company")',
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Manufacturer, value: item.Manufacturer };
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
})
},
});
});
Here is my ajax call method
[HttpPost]
public JsonResult GetRecord(string prefix)
{
BAL_Branches ObjBranch = new BAL_Branches();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
List<ManufacturerCertificates> menufact = new List<ManufacturerCertificates>();
ds = ObjBranch.GetManufacturerCertsForAutocomplate(prefix, Convert.ToInt64(Session["BranchID"]));
dt = ds.Tables[0];
// mm.BranchesList[i].ManufactCertsList = Common.ConvertDataTable<ManufacturerCertificates>(dt);
foreach (DataRow dr in ds.Tables[0].Rows)
{
menufact.Add(new ManufacturerCertificates
{
Manufacturer = dr["Manufacturer"].ToString(),
ID =Convert.ToInt64( dr["ID"].ToString())
});
}
// menufact = dt.ToList<ManufacturerCertificates>();
return Json(menufact, JsonRequestBehavior.AllowGet);
}
The ajax method returns correct values but autocomplete textbox is not appear. any suggestions?
Thanks is advance.
I have resolve this my self as change $(document).ready() function to $(window).load()
$(window).load(function () {
$("#Manufacturer").autocomplete({
source: function (request, response) {
debugger
$.ajax({
url: '#Url.Action("GetRecord", "Company")',
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Manufacturer, value: item.Manufacturer };
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
})
},
});
});
and apply z-index
.ui-widget-content {
z-index: 99999 !important;
}
now it will work fine for me.
If a user is typing something into a textbox on a form, and what they are typing in starts to match a value that is already in the database, how do I get the textbox to give the option to auto-fill the rest of what the user wants to type in based on the value that is already in the database?
Consider I have this table(name of table: Person) in my database:
|ID| |FirstName| |LastName|
1 John Smith
2 Tom Jones
3 James Davis
and on the form where the user wants to create a new Person they start to type in jo into the FirstName textbox.. how do i get the textbox to give the option to autofill the hn and capitalize the first letter to spell John?
Any help is appreciated.
UPDATE:
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create([Bind(Include = "ID,text,subcategory")] Activity codeAC, string term)
{
if (ModelState.IsValid)
{
var result = (from r in db.Activities
where r.subcategory.ToUpper().Contains(term.ToUpper())
select new { r.subcategory }).Distinct();
db.Activities.Add(codeAC);
db.SaveChanges();
return Json(result, JsonRequestBehavior.AllowGet);
}
return Json(codeAC);
}
Script:
<script type="text/javascript">
$(document).ready(function () {
$('#Categories').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Activities/Create",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.subcategory, value: item.subcategory };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
CSHTML:
<div class="form-group">
#Html.LabelFor(model => model.subcategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.subcategory, new { htmlAttributes = new { #id = "Categories", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.subcategory, "", new { #class = "text-danger" })
</div>
</div>
I figured it out. I didn't know that I couldn't incorporate this into my Create ActionResult.. so I created a separate JsonResult method and it is working.
Controller:
public JsonResult AutoCompleteCategory(string term)
{
var result = (from r in db.Activities
where r.subcategory.ToUpper().Contains(term.ToUpper())
select new { r.subcategory }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
SCRIPT:
<script type="text/javascript">
$(document).ready(function () {
$('#Categories').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Activities/AutoCompleteCategory",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.subcategory, value: item.subcategory };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>