JQuery ui autocomplete in a MVC partial view only works once - javascript

I've been trying to get autocomplete to work for my partial view using JQuery ui. The partial view is updated using AJAX.
The problem is that the autocomplete only works up until the point where the partial view is updated.
This is my partial view
<div id="tagList">
#using (Ajax.BeginForm("AddToTagList", new { urlLocation = Model.UrlLocation }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "tagList" }))
{
if (Model.TagList != null)
{
<div class="form-group">
#Html.LabelFor(model => model.Tag.Text, "Tags", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-xs-10">
<div class="input-group" style="max-width: 300px;">
#Html.EditorFor(model => model.Tag.Text, new { htmlAttributes = new { #class = "form-control", #id = "search_term" } })
#Html.ValidationMessageFor(model => model.Tag.Text, "", new { #class = "text-danger" })
<div class="input-group-btn">
<button type="submit" value="Add Tag" class="btn btn-default">+</button>
</div>
</div>
</div>
</div>
}
}
</div>
This is my JavaScript
$(document).ready(function () {
$("#search_term").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Tag/SearchAutoComplete",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Text };
}));
}
});
},
});
});
and this is my autocomplete search action
public JsonResult SearchAutoComplete(string term)
{
using (IDocumentSession session = RavenDbConfig.RavenDBDocumentStore.OpenSession())
{
var results = session.Query<Tag>().Where(x => x.Text.StartsWith(term)).ToList();
return Json(results,JsonRequestBehavior.AllowGet);
}
}
So, my question is, how can i make this work even after the partial view has been updated once?

Your problem is when you reload your PartialView you basicaly delete some part of DOM in your html document and create new one. And all your bindings that you add in $(document).ready() event will be lost.
One of the posible solutions for this problem is to place your autocomplete init code in addition to .ready() event in jquery .ajaxSuccess() global event becouse you reload your PartialViews via Ajax. Like this:
$(document).ajaxSuccess(function() {
$("#search_term").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Tag/SearchAutoComplete",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Text };
}));
}
});
},
});
});
That way you will init your autocomplete every time you reload PartialView.

Related

Dynamic DropDownList in ASP.NET MVC NO ACTION RESULT CREATE()

I CANNOT CREATE CASCADING DROPDOWN IN ACTIONRESULT CREATE, ONLY IN ACTION RESULT INDEX IT WORKS
THERE GOES THE CODE
CONTROLLER
public class PessoasController : Controller
{
private GestarkContext db = new GestarkContext();
// GET: Pessoas
public ActionResult Index()
{
ViewBag.Gabinetes = new SelectList(db.Gabinetes, "GabineteId", "Nome");
var pessoageral = db.Pessoas.Include(a => a.gabojecto).Include(a => a.nivelojecto);
return View(pessoageral.ToList());
}
[HttpPost]
public JsonResult getDistricts(int gbtID)
{
List<Departamento> DepartamentoList = db.Departamentoes.Where(p => p.GbtId == gbtID).ToList();
return Json(DepartamentoList, JsonRequestBehavior.AllowGet);
}
VIEW INDEX - IT WORKS HERE
<script>
$(function () {
$('#Gabinetes').change(function () {
var gbtID = $(this).val();
$.ajax({
type: "post",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "getDistricts",
data: "{gbtID:'" + gbtID + "'}",
success: function (data) {
$('#DepartamentoList').empty();
$('#DepartamentoList').append('<option selected="selected" value="">Select Departamento</option>')
$.each(data, function (i, d) {
$('#DepartamentoList').append('<option value=' + d.DircId + '>' + d.Depto + '</option>');
});
},
failure: function (data) {
alert('error occured');
}
});
});
});
</script>
<h2>Lista de Funcioários Registrados</h2>
<br />
<label class="col-md-2 control-label">Gabinete</label>
<div class="col-md-5">
#Html.DropDownList("Gabinetes", null, htmlAttributes: new { #class = "form-control" })
</div>
<div class="form-group">
<label class="col-md-2 control-label">Departamento</label>
<div class="col-md-4">
<select id="DepartamentoList" name="DepartamentoList" class="form-control"></select>
</div>
</div>
<p>
#Html.ActionLink("Visualizar Formulário", "Index", "Principal", null, new { #class = "btn btn-default" }) | #Html.ActionLink("Adicionar Novo", "Create", null, new { #class = "btn btn-primary" }) | #Html.ActionLink("Exportar em Excel", "ExportToExcel", null, new { #class = "btn btn-success" })
</p>
...........
NOW ON VIEW CREATE DOES NOT WORK
I write the code as I do in index, but it doesn't work
I NEED YOUR HELP PLEASE

How can I get my jquery autocomplete to fill in multiple fields in MVC?

I am trying to setup an autocomplete in jquery that gets information from a user in Active Directory. A user can type in a few letters of a person's last name, and what returns is a 2D list (List>) that contains all the people whose last name starts with those letters. Each List holds the first, middle, last name and AD name of a person. And of course, each List> element represents a person.
I have no issues getting the data in jquery. The problem is that I can't seem to figure out how to make it populate the Employee_Name and Employee_Name_AD fields with the information in this array once the user clicks on a name from the list. This is my jquery code:
#section page {
<script type="text/javascript">
$(document).ready(function () {
var name;
var adname;
$("#TESTING").autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Employees/GetUserList",
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
name = item[0] + " " + item[1] + " " + item[2];
adname = item[3];
return { label: name, data: [name, adname] };
}))
},
select: function (event, ui) {
$('#Employee_Name').val(ui.data.item.data[0]);
$('#Employee_Name_AD').val(ui.data.item.data[1]);
}
})
},
});
})
</script>
}
And on the same page, here is the accommodating Razor code:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-10">
#Html.TextBox("TESTING")
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name_AD, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name_AD, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name_AD, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
I found something super close to what I want thanks to stack overflow: http://jsbin.com/vasuliru/2/edit?html,js,output
The problem with the previous example is that the data is declared on the page itself, not pulled from a data source. How can I modify my code to get it to do what I want?
I was finally about to find a solution, after I came across something in php: Jquery ui autocomplete on multiple input fields with ajax results.
My final code is this:
#section page {
<script type="text/javascript">
$(document).ready(function () {
var name;
var adname;
$("#UserLookup").autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Employees/GetUserList",
type: "POST",
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
name = item[0] + " " + item[1] + " " + item[2];
adname = item[3];
console.log(adname);
return { label: name, data: item }
}));
}
});
},
select: function (event, ui) {
console.log(ui.item);
$(this).val(ui.item.label);
var userid = ui.item.value;
console.log("Here is the userid:");
console.log(item);
console.log(ui.item.data[3]);
$('#Employee_Name').val(ui.item.value);
$('#Employee_Name_AD').val(ui.item.data[3]);
}
});
});
</script>
}

change event not perform on datepicker through jquery

I want to pass a selected date to controller for performing operation on database.
But my jquery is not functioning properly..
Can anyone help me solve the issue?
here is my View code :
<div class="form-group">
#Html.EditorFor(model => model.DT, new { htmlAttributes = new { #class = "form-control datepicker", placeholder = "PRC Date", Value = DateTime.Now.ToShortDateString() } })
#Html.ValidationMessageFor(model => model.DT, "", new { #class = "text-danger" })
</div>
here is my jQuery Code..
$("#DT").on("change", function () {
debugger
var selectedValue = $(this).val();
alert(selectedValue);
$.ajax({
type: "POST",
url: '#Url.Action("DateWiseData", "ProcessWax")',
contentType: "application/json; charset=utf-8",
data: selectedValue,
dataType: "json",
success: function (data) {
if (data.status == true) {
alert('Successfully done.');
}
else {
alert('Failed');
}
},
//error: function () { alert('Error. Please try again.'); }
});
});
HTML:
<div class="form-group">
#Html.TextBoxFor(model => model.DT, new { htmlAttributes = new { #class = "form-control datepicker", placeholder = "PRC Date", Value = DateTime.Now.ToShortDateString() } })
</div>
jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
alert();
$("#DT").on("change", function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.ajax({
type: "POST",
url: "/ProcessWax/DateWiseData?Date=" + selectedValue ,
contentType: "application/json; charset=utf-8",
data: selectedValue,
dataType: "json",
success: function (data) {
if (data.status == true) {
alert('Successfully done.');
}
else {
alert('Failed');
}
},
//error: function () { alert('Error. Please try again.'); }
});
});
</script>
Controller:
[HttpPost]
public ActionResult DateWiseData(DateTime Date)
{
}
If you want that select a date from Jquery datepicker and send it to your controller you can simply bind your datepicker to your controller.
HTML :
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<div class="form-group">
#Html.EditorFor(model => model.DT, new { htmlAttributes = new { #class = "form-control datepicker", placeholder = "PRC Date", Value = DateTime.Now.ToShortDateString() } })
#Html.ValidationMessageFor(model => model.DT, "", new { #class = "text-danger" })
</div>
<button type="submit"></button>
}
Controller :
[HttpPost]
public ActionResult Index(YourModel t)
{
var date = t.DT;
//Do whatever you want (ex. save in database)
return View();
}
UPDATE:
Please Try this code:
$( function() {
$( "#DT" ).datepicker()
.on("change", function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.ajax({
type: "POST",
url: '#Url.Action("DateWiseData", "ProcessWax")',
contentType: "application/json; charset=utf-8",
data: selectedValue,
dataType: "json",
success: function (data) {
if (data.status == true) {
alert('Successfully done.');
}
else {
alert('Failed');
}
}
});
});
} );
As you can see in the code you forgot to put .datepicker() after $("#DT") .

MVC ASP Autocomplete

I know there are a few posts on this matter, but I couldn't get any option working. I'm going nuts.
I'm pretty new in MVC and JavaScript. I get the following error in my console:
FamilyStudentJS.js:20 Uncaught TypeError: $(...).autocomplete is not a function
at HTMLDocument. (FamilyStudentJS.js:20)
at fire (jquery-1.12.4.js:3232)
at Object.fireWith [as resolveWith] (jquery-1.12.4.js:3362)
at Function.ready (jquery-1.12.4.js:3582)
at HTMLDocument.completed (jquery-1.12.4.js:3617)
I tried many references. Still, my C# function isn't launched. When I manually run it, it works fine.
My HTML code:
<div class="form-group">
#Html.LabelFor(model => model.FamilyNum, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" id="fs">
<label> <input type="checkbox" id="FamilyCheckBox"> Family attached? </label>
<div id="familysection" style="display:none" >
<span>
<input type="text" id="FamilyIDTextBox" />
</span>
</div>
#Html.ValidationMessageFor(model => model.FamilyNum, "", new { #class = "text-danger" })
</div>
</div>
JavaScript:
$(document).ready(function () {
$("#FamilyCheckBox").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Students/GetSearchValue",
type: "POST", dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.startfrom };
}));
}
});
},
messages: { noResults: "", results: "" }
});
})
C#:
public JsonResult GetSearchValue(string search)
{
var temp = new FamilyViewModel();
EzappContext db = new EzappContext();
List<Family> allsearch = db.Families.Where(x => x.FamilyName.Contains(search)).Select(x => new Family
{
FamilyName = x.FamilyName,
FamilyNum = x.FamilyNum
}).ToList();
return new JsonResult { Data = allsearch, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Main view stacks on the same page after calling partial view

I have this action that returns different partial view based on the selected value from the drop down list.
Controller:
[HttpPost]
public ActionResult Foo(SomeViewModel VM)
{
var model = VM
if (Request.IsAjaxRequest())
{
if (model.SelectedValue == 1 || model.SelectedValue == 2 || model.SelectedValue == 3)
{
// ...
return PartialView("PartialView1", model);
}
else if (model.SelectedValue == 4)
{
// ...
return PartialView("PartialView2", model);
}
else (model.SelectedValue == 5)
{
// ...
return PartialView("PartialView3", model);
}
}
return View(model);
}
Main View:
<script src="~/Scripts/jquery-3.2.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div>
<h2>Paint Computation</h2>
#using (Ajax.BeginForm("Foo", "Controller",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "Result"
}))
{
<div class="col-md-10">
<h5>Type of Paint</h5>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.PaintType, "Value", "Text"),
"Please Select", htmlAttributes: new { #class = "form-control" })
</div>
<br />
// Some HTML helpers
<input type="submit" value="Compute" class="btn btn-default" id="Submit" />
</div>
}
</div>
//This is how I render my partial view using jQuery in my main View:
<div id="Result">
<hr />
</div>
<script type="text/javascript">
$(document).ready(function () {
$('#Submit').click(function () {
$('#Result').load('/Controller/Foo');
});
});
</script>
Whenever I clicked the button, the partial view appears, but when I clicked it again for the 3rd or 4th time, the main view content stacks on the same main view. I tried to use the inspect element and that's how I determined that it stacks the same main view elements.
Is my way of calling the partial view is right? As much as possible I want to use ajax for calling the partial view every time the button is clicked. Please guide me to correct it. Thanks.
Here's the of the problem.
<script type="text/javascript">
$(document).ready(function () {
$('#Submit').click(function () {
$.ajax({
type: 'POST',
url: '/Controller/Foo',
cache: false,
contentType: "application/html; charset=utf-8",
dataType: 'html',
success: function (result) {
$('#Result').html(result);
}
});
});
});
</script>
Now it works. I changed my code and use the code above. I use .html() rather than .append() or .replaceWith(). Now every time i click the button, it changes the <div id = "Result> content.

Categories

Resources