Autocomplete dropdownlist not working - javascript

I went through a lot of guides and stacloverflow posts, but i still don't manage to make it work. I'm still new in javascript, and it's hard for me to figure if it's the script or not.
The main issue i got is the fact I'm not able to debbug it properly, i mean, i can't find where and why it's not working, i just know it doesn't.
Here is my Controller :
Entities db = new Entities();
// GET: DynamicListe
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Index(string Prefix)
{
//Searching records from list using LINQ query
var client = (from c in db.Clients
where c.Nom.Contains(Prefix)
select new { c.Nom });
return Json(client, JsonRequestBehavior.AllowGet);
}
Here is my View :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#client").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
for (var i = 0; i < data.length ; i++) {
customer[i] = { label: data[i].Value, Id: data[i].Key }
}
}
});
response(customer);
},
messages: {
noResults: "", results: ""
}
});
})
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="client">
<div class="col-md-12">
#Html.TextBox("client")
</div>
</div>
</div>
}
I got the right amount of answers (when i press "w" i got 13 results which is correct according to my db), but it's all empty. I've tried severals ways to display the json datas, but i don't know how to make it work..
Edit : correct controller and view :
view :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#client").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Text, value: item.Value};
}))
}
});
},
messages: {
noResults: "", results: ""
}
});
})
</script>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
<div class="client">
<div class="col-md-12">
#Html.TextBox("client")
</div>
</div>
</div>
}
controller :
[HttpPost]
public JsonResult Index(string Prefix)
{
List<SelectListItem> list = new List<SelectListItem>();
var client = (from c in db.Clients
where c.Nom.Contains(Prefix)
select c).ToArray();
for (int i = 0; i < client.Length; i++)
{
list.Add(new SelectListItem
{
Text = client[i].Nom,
Value = client[i].ClientID.ToString()
});
}
return Json(list, JsonRequestBehavior.AllowGet);
}

You're returning your response before it has been received.
In here
source: function (request, response) {
var customer = new Array();
$.ajax({
url: "/DynamicListe/Index",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
for (var i = 0; i < data.length ; i++) {
customer[i] = { label: data[i].Value, Id: data[i].Key }
}
}
});
response(customer);
},
Move the line response(customer) inside the ajac success callback.

You textbox does not have an ID. you have to add for yout textbox : #Id="client"

Related

Update List Model with Ajax ASP .NET MVC5

Can somebody give me a hint how to pass a list from the controller to Model list in view page after call the Action Result whit ajax in page. (Meaning update current list model with ajax call back result)?
This is my default load view page code:
#model List<ChargeSystem.Models.Message>
#foreach (var item in Model)
{
<div class="container1">
<p>#item.Msg</p>
<span class="time-right">#item.MsgDate</span>
</div>
}
</div>
<div class="divContinMsg">
<input type="text" id="txtMsg" name="txtMsg" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#txtMsg").keyup(function (e) {
if (e.keyCode == 13) {
$.ajax(
{
url: '/User/ajaxContactAdmin?msg=' + $("#txtMsg").val(),
type: 'Post',
data: "",
contentType: false,
success: function (result) {
//What can i do????
},
error: function () {
alert("error");
}
})
};
});
});
</script>
This is the Ajax call action result:
public ActionResult ajaxContactAdmin(string msg)
{
var result = new { model = messageRepository.Select().ToList()};
return Json(result, JsonRequestBehavior.AllowGet);
}
So, How can i refresh the model after ajax call back?
So what you would do is append the result to the existing result set.
Firstly I would add a container for easier reference, secondly you would add the item to the container:
#model List<ChargeSystem.Models.Message>
<div id="listContainer">
#foreach (var item in Model)
{
<div class="container1">
<p>#item.Msg</p>
<span class="time-right">#item.MsgDate</span>
</div>
}
</div>
</div>
<div class="divContinMsg">
<input type="text" id="txtMsg" name="txtMsg" />
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#txtMsg").keyup(function (e) {
if (e.keyCode == 13) {
$.ajax(
{
url: '/User/ajaxContactAdmin?msg=' + $("#txtMsg").val(),
type: 'Post',
data: "",
contentType: false,
success: function (result) {
$('#listContainer').append('<div class="container1">'+
'<p>' + result.Msg + '</p>'+
'<span class="time-right">' + result.MsgDate +'</span>'+
'</div>');
},
error: function () {
alert("error");
}
})
};
});
});
</script>
It looks like you want to enter information in your text box and save and update it in the view.
I think you can do this.
Here is an example:
Your Controller:
public IActionResult GetUser ()
{
var messages = context.Messages.ToList();
return View(messages);
}
[HttpPost]
public IActionResult ajaxContactAdmin(string msg)
{
var message = new Message
{
Msg = msg,
MsgDate = DateTime.Now
};
context.Add(message);
context.SaveChanges();
return Json(message);
}
Js in your View:
#section scripts{
<script>
$(document).ready(function () {
$("#txtMsg").keyup(function (e) {
if (e.keyCode == 13) {
var msg = document.getElementById("txtMsg").value
$.ajax(
{
url: '/Home/ajaxContactAdmin?msg=' + $("#txtMsg").val(),
type: 'Post',
data: { "msg": msg},
contentType: false,
success: function (message)
{
console.log(message);
window.location.reload();
},
error: function () {
alert("error");
}
})
};
});
});
</script>
}
Result display:

Parent View toggles Partial Views - on click triggers multiple times

I have Parent View and 2 Partial Views. I have buttons on each partial view that is registered for an on click event on the parent page. They do ajax calls to get their respective partial view.
Controller
[HttpPost]
public ActionResult GetEmployee(int id)
{
HumanResourcesManager man = new HumanResourcesManager();
var emp = man.GetEmployee(id);
EmployeeModel empModel = new EmployeeModel(emp);
return PartialView("_EmployeeDetails", empModel);
}
[HttpPost]
public ActionResult GetEmployeeForEdit(int id)
{
HumanResourcesManager man = new HumanResourcesManager();
var emp = man.GetEmployee(id);
ViewBag.States = man.GetStates();
EmployeeModel empModel = new EmployeeModel(emp);
return PartialView("_EmployeeEdit", empModel);
}
Parent View
#model HumanResources.Web.Models.EmployeeModel
<p>
Selected Employee: #Html.TextBox("EmployeeSearch")
</p>
<script type="text/javascript">
$("#EmployeeSearch").autocomplete({
source: function (request, response) {
                $.ajax({
url: "#(Url.Action("FindEmployee", "Employee"))",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
response($.map(data, function (item) {
return { label: item.DisplayName, value: item.DisplayName, id: item.Id };
                        }))
                    }
                })
},
select: function (event, ui) {
if (ui.item) {
GetEmployeeDetails(ui.item.id);
}
}
});
function GetEmployeeDetails(id) {
$("partialView").empty();
$.ajax({
type: "POST",
url: "#(Url.Action("GetEmployee", "Employee"))",
data: { id: id },
success:function(result)
{
$("#partialView").html(result);
},
failure: function (response) {
alert(response.d);
}
});
#*$(document).on('click', "#empEdit", function(){
$.ajax({
type: "POST",
url: "#(Url.Action("GetEmployeeForEdit", "Employee"))",
data: #Html.Raw(Json.Encode(Model)),
success:function(result)
{
$("#partialView").html(result);
},
failure: function (response) {
alert(response.d);
}
})
});*#
$(document).on('click', "#empEdit", function(){
$.ajax({
type: "POST",
url: "#(Url.Action("GetEmployeeForEdit", "Employee"))",
data: {id: $("#editEmployeeId").val()},
success:function(result)
{
$("#partialView").html(result);
},
failure: function (response) {
alert(response.d);
}
})
});
$(document).on('click', "#empEditCancel", function(){
GetEmployeeDetails($("#editEmployeeId").val());
});
}
</script>
<div id="partialView">
</div>
Partial View - Details
The details is intended to display details and an edit button. The JavaScript I have in the Parent View.
#model HumanResources.Web.Models.EmployeeModel
#{
Layout = null;
}
#Html.HiddenFor(model => model.Employee.Id, new { id = "editEmployeeId" })
#Html.DisplayTextFor(model => model.Employee.FirstName)
<input id="empEdit" type="button" value="Edit"/>
Partial View - Edit
The Edit View displays the same values as the details partial view, but as editable fields.
#model HumanResources.Web.Models.EmployeeModel
#{
Layout = null;
}
#using (Html.BeginForm("Save", "Employee")) {
#Html.HiddenFor(model => model.Employee.Id, new { Id = "editEmployeeId" })
<div class="container">
<input type="submit" value="Save" />
<input id="empEditCancel" type="button" value="Cancel"/>
</div>
}
My Issue
Editing and cancelling (toggling between the two partial views) once works fine. Editing and cancelling more than once it seems that the functions for the on click are called increasingly number of times by a factor of 2. Causing the alerts to be called multiple times.
What am I doing wrong?

MVC dropdown list with json data and chosen

I'm trying to populate dropdown list with jsonResult data on a second list
on change event. That works just fine. But I also want to use chosen on that list, and with that list is empty. It looks like chosen is not picking up list update. I'm pretty new in this so please help
First list:
<div class="col-md-10">
#Html.DropDownList("tipopreme_TipOpremeID", null, htmlAttributes: new { #class = "form-control", #onchange = "PopuniDropOpreme()" })
</div>
Second List:
#Html.DropDownListFor(x => x.ModelOpreme_ModelOpremeID, new SelectList(Enumerable.Empty<SelectListItem>()))
Controller:
public JsonResult getOpremaPoTipu(int? tipid)
{
List<SelectListItem> lista = new List<SelectListItem>();
if (tipid != null)
{
foreach (var item in db.ModelOpremes.Where(x=>x.TipOpreme_TipOpremeID==tipid))
{
lista.Add(new SelectListItem { Text = item.PunNaziv, Value = item.ModelOpremeID.ToString()});
}
}
else
{
foreach (var item in db.ModelOpremes)
{
lista.Add(new SelectListItem { Text = item.PunNaziv, Value = item.ModelOpremeID.ToString() });
}
}
return Json(lista, JsonRequestBehavior.AllowGet);
}
Script:
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/chosen.jquery.min.js"></script>
<link href="~/Content/chosen.min.css" rel="stylesheet" />
<script type="text/javascript">
$(".chzn-select").chosen();
$("#ModelOpreme_ModelOpremeID").chosen();
function PopuniDropOpreme() {
var tip = $("#tipopreme_TipOpremeID").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Opremas/getopremapoTipu?selectedValue=" + tip,
data: "{}",
dataType: "Json",
success: function (data) {
$('.ddlProjectvalue').find('option').remove();
$(data).each(function (index, item) {
$("#ModelOpreme_ModelOpremeID").append($('<option></option>').val(item.Value).html(item.Text));
});
$("ModelOpreme_ModelOpremeID").chosen("destroy").chosen();
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
}
</script>
You got some errors in your code:
- url: "/Opremas/getopremapoTipu?selectedValue=" + tip, //wrong param name
- $('.ddlProjectvalue').find('option').remove(); //wrong id
They should be:
- url: "/Opremas/getopremapoTipu?tipid=" + tip
- $('#ModelOpreme_ModelOpremeID').find('option').remove();
You can follow my sample. Hope to help, my friend!
public class Test
{
public int Id { get; set; }
public string Value { get; set; }
}
public JsonResult GetData(int? selectedValue)
{
List<SelectListItem> lista = new List<SelectListItem>();
if (selectedValue != null)
{
foreach (var item in Data().Where(t=>t.Id == selectedValue))
{
lista.Add(new SelectListItem
{
Text = item.Id.ToString(),
Value = item.Value
});
}
}
else
{
foreach (var item in Data())
{
lista.Add(new SelectListItem { Text = item.Id.ToString(), Value = item.Value.ToString() });
}
}
return Json(lista, JsonRequestBehavior.AllowGet);
}
private List<Test> Data()
{
var data = new List<Test>
{
new Test{Id = 1, Value = "A1"},
new Test{Id = 1, Value = "A2"},
new Test{Id = 1, Value = "A3"},
new Test{Id = 1, Value = "A4"},
new Test{Id = 2, Value = "B1"},
new Test{Id = 3, Value = "C1"},
new Test{Id = 4, Value = "D1"},
};
return data;
}
And code in View:
#{
ViewBag.Title = "About";
}
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css">
</head>
<body style="margin-top:50px;">
<script type="text/javascript">
$(function () {
$(".chzn-select").chosen();
$("#ModelOpreme_ModelOpremeID").chosen();
$(".chzn-select").chosen().change(function () {
var id = $(this).val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "/Home/GetData?selectedValue=" + id,
data: "{}",
dataType: "Json",
success: function (data) {
$('#ModelOpreme_ModelOpremeID').find('option').remove();
$(data).each(function (index, item) {
$("#ModelOpreme_ModelOpremeID").append($('<option></option>').val(item.Text).html(item.Value));
});
$("#ModelOpreme_ModelOpremeID").chosen("destroy").chosen();
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
});
});
</script>
<select class="chzn-select" name="faculty" style="width:200px; margin:10%;">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<br />
<select id="ModelOpreme_ModelOpremeID" style="width:200px; ">
</select>
</body>
</html>

Ajax call to Controller arrives empty in MVC 4

I'm trying to populate one select when the onchange of another select is called. Below is what I have built. My GetLine ActionResult breakpoint is being hit, but the parameter breweryCode is null. The method errors at that point. What am I missing?
Controller:
public ActionResult Index()
{
List<Brewery> breweries = BuildMockBrewery();
ViewBag.Breweries = new SelectList(breweries.AsEnumerable(), "BreweryCode", "BreweryDescription");
return View();
}
public ActionResult GetLine(string breweryCode)
{
List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
return Json(pLine);
}
Index.cshtml:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript">
function GetLine(_breweryCode) {
var url = '/Report/GetLine/';
$.ajax({
url: url,
data: { breweryCode: _breweryCode },
cache: false,
type: "POST",
success: function (data) {
alert('called');
var markup = '<option value="0">Select Line</options>';
for (var i = 0; i < data.length; i++) {
markup += '<option value="' + data[i].Value + '">' + data[i].Text + '</options';
}
$('#LineSelect').html(markup).show();
},
error: function (response) {
alert('fail' + ' ' + _breweryCode);
}
});
}
</script>
<div id="report-description">
#using (Html.BeginForm("Index", "Report", FormMethod.Post))
{
#Html.DropDownList("BreweryCode", (SelectList)ViewBag.Breweries, "Select Brewery", new { #class = "ui-select", #ID = "BrewerySelect", #onchange = "javascript:GetLine(this.Value);" })
<select class="ui-select" id="LineSelect" name="ReportSelect">
</select>
}
In your #onchange attribute, change this.Value to this.value
Try add
[HttpPost]
public ActionResult GetLine(string breweryCode)
{
List<PackagingLine> packagingLines = BuildMockLine(breweryCode);
SelectList pLine = new SelectList(breweryCode, "LineNumber", "Descriptions", 0);
return Json(pLine);
}
so GetLine can be able to process POST request
Please add datatype as well:
dataType: 'html', or dataType: 'json'
and add http method in a controller
[HttpPost]
public ActionResult GetLine(string breweryCode)
{
}
Also, make sure whether value _breweryCode is coming in below function
function GetLine(_breweryCode)
{
}
Take below code as sample
$.ajax({
type: "POST",
url: your url,
dataType: 'json',
data: JSON.stringify({ id: '2' }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert('hello');
}
});

Autocomplete textbox in asp.net mvc4 using ajax and jQuery

I am trying to fetch company name in textbox as autocomplete. When I run my project, Ajax will call the success function, and the record is also fetched correctly, but there are no autocomplete suggestions in the textbox.
My view is:
$("#idcompanyname").autocomplete({
source: function (request, response) {
var customer = new Array();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("Companymap", "admin")',
data: "{'term':'" + document.getElementById('idcompanyname').value + "'}",
dataType: "json",
success: function (data) {
alert(data)
response($.map(data, function (v, i) {
var text = v.vcCompanyName;
alet(text)
if (text && (!request.term || matcher.test(text))) {
return {
label: v.vcCompanyName,
value: v.kCompanyId
};
}
}));
},
error: function(result) {
alert("No Match");
}
});
}
});
}
Here is Method on controller:
var query = db.tbaccounts.Where(t => t.vcCompanyName.ToLower()
.StartsWith(term)).ToList();
List<string> lst = new List<string>();
foreach (var item in query)
{
lst.Add(item.vcCompanyName);
}
return Json(lst, JsonRequestBehavior.AllowGet);
Here is the referred Javascript:
<script src="~/script/jquery-2.0.3.js"></script>
<script src="~/script/jquery-ui.js"></script>
<script src="~/js/jquery-1.10.2.js"></script>
<script src="~/js/jquery-ui.js"></script>
Please try removing
~/script/jquery-2.0.3.js
from the script references in your application, and that should work for you....

Categories

Resources