I'm working on autocomplete JQuery function to populate student names in the text box. I've utilized every related JQuery library to make the autocomplete function work. When i press F12, it always throws an error which is "autocomplete is not a function". Below is my code that I'm running.
StudentBatch.cshtml
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
alert("This is autocomplete function");
});
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response) {
$.ajax({
url: "/Student/Create",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
try {
response($.map(data, function (item) {
return { label: item.StudentName, value: item.StudentName };
}))
} catch (err) { }
}
})
},
messages: {
noResults: "jhh", results: "jhjh"
}
});
});
</script>
StudentController.cs
[HttpPost]
public JsonResult Create(string Prefix)
{
CreateUser user = new CreateUser();
string stdid = "fae30ef0-08b2-4490-a389-3c8eb0a7cc53";
var StudentList = user.GetAllUsers().ToList().Where(u => u.FirstName == Prefix && u.usertypeid == stdid).ToString();
return Json(StudentList, JsonRequestBehavior.AllowGet);
}
I have created similar demo which you are creating.
Model
public class CreateUser
{
public string StudentName { get; set; }
public string StudentId { get; set; }
}
Controller
public class StudentController : Controller
{
// GET: Student
public ActionResult Create()
{
return View();
}
[HttpPost]
public JsonResult Create(string prefix)
{
List<CreateUser> studentList = new List<Models.CreateUser>()
{
new CreateUser { StudentId = "1" , StudentName = "Student1"},
new CreateUser { StudentId = "2" , StudentName = "Student2"},
new CreateUser { StudentId = "3" , StudentName = "Student3"},
new CreateUser { StudentId = "4" , StudentName = "Student4"},
new CreateUser { StudentId = "5" , StudentName = "Student5"},
new CreateUser { StudentId = "6" , StudentName = "Student6"},
new CreateUser { StudentId = "7" , StudentName = "Student7"},
};
var searchlist = (from student in studentList
where student.StudentName.Contains(prefix)
select student).ToList();
return Json(searchlist, JsonRequestBehavior.AllowGet);
}
}
View
#model WebApplication6.Models.CreateUser
#{
Layout = null;
}
<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" />
<style>
.ui-autocomplete {
max-height: 100px;
overflow-y: auto;
/* prevent horizontal scrollbar */
overflow-x: hidden;
}
/* IE 6 doesn't support max-height
* we use height instead, but this forces the menu to always be this tall
*/
* html .ui-autocomplete {
height: 100px;
}
.ui-autocomplete-input {
width: 300px;
}
</style>
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/Create",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.StudentName, value: item.StudentName };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
Output
Related
I tried to use datatable with my project and I always got undefined when data return from the controller while I checked the controller already returned 1000 records
this is my controller
[HttpGet]
public JsonResult get_Student_Info()
{
var model = (from C in _db1.ClassesInfos
select new Classes
{
ClassId = C.Id,
ClassCounty = C.ClassCounty ?? "",
ClassLocation = C.ClassLocation,
ClassSize = C.ClassSize ?? 0,
ClassDate = C.ClassDate.ToString(),
//ClassMonitorId = C.MonitorId,
//ClassActive = C.Active ?? 0,
//ClassLastModifedDate = C.LastModifiedDate.ToString(),
//ClassPasscode = C.Passcode,
//ClassType = C.ClassType
}).FirstOrDefault();
return Json(mymodel, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
and this is my view
$(function () {
$.ajax({
type: "GET",
//url: "/Instructor/get_Student_Info",
url: '#Url.Action("get_Student_Info", "Instructor")',
mimeType: 'json',
async: true,
success: function(data) {
$.each(data, function (i, data) {
alert(data.ClassCounty);
alert(data.ClassLocation);
var body = "<tr>";
body += "<td>" + data.ClassCounty + "</td>";
body += "<td>" + data.ClassLocation + "</td>";
body += "</tr>";
$( "#ClasssInfo tbody" ).append(body);
});
/*DataTables instantiation.*/
$( "#ClasssInfo" ).DataTable();
},
});
});
In asp.net mvc, it should be:
Model:
public class Class
{
public string ClassCounty { get; set; }
public string ClassLocation { get; set; }
}
View:
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'ClassCounty' },
{ 'data': 'ClassLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
//must be list model
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model, JsonRequestBehavior.AllowGet);
}
In asp.net core/.net 5, it should be:
View:
Note: In asp.net core/.net 5, the response json format is camel case.
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'classCounty' }, //difference here..should be camel case
{ 'data': 'classLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model);
}
I need to get a list permissao when I select a group, I made the methods but when I select the group, it returns me an error.
PermissaoGrupo/ObterPermissoesAdd:1 Failed to load resource: the
server responded with a status of 400 ()
View
#model RKMES.Models.ViewModel.PermissaoGrupoViewModel
<script type="text/javascript" src="assets/js/plugins/forms/inputs/duallistbox.min.js"></script>
<script type="text/javascript" src="assets/js/pages/form_dual_listboxes.js"></script>
<h2>Index</h2>
<div class="form-group">
#*<label asp-for="Grupos" class="control-label">Grupo</label>*#
#*<select class="custom-select custom-select-sm" asp-items="#(new SelectList(Model.Grupos,"Id","Nome"))"></select>*#
Grupos
#Html.DropDownList("Grupos", new SelectList(Model.Grupos,"Id", "Nome"))
</div>
<!-- Filtered results -->
<div class="panel panel-flat">
<div class="panel-heading">
<h5 class="panel-title">Filtered results</h5>
</div>
<div class="panel-body">
#*<select multiple="multiple" class="form-control listbox-no-selection" asp-items="#(new SelectList(Model.Permissoes,"Id","Nome"))"></select>*#
#Html.DropDownList("Permissoes", new SelectList(Enumerable.Empty<SelectListItem>(), "Id", "Nome"))
</div>
</div>
<!-- /filtered results -->
<script type="text/javascript">
$(document).ready(function () {
$('#Grupos').change(function () {
var idGrupo = $('#Grupos').val();
if (idGrupo > 0) {
$.post('#Url.Action("ObterPermissoesAdd", "PermissaoGrupo")', { 'idGrupo': idGrupo }, function (data) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
$('#Permissoes').append('<option value="' +data[i].Id+ '">' + data[i].Nome+ '</option>');
}
}
});
}
});
});
</script>
PermissaoGrupoController
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ObterPermissoesAdd(int idGrupo)
{
return Json(_grupoContext.GetPermissoesAdd(idGrupo));
}
GrupoService
public async Task<List<Permissao>> GetPermissoesAdd(int id)
{
return await _context.Grupo_Permissao_Permissao
.Where(x => x.Grupo_PermissaoId == id)
.Select(x => x.Permissao)
.ToListAsync();
}
Model
namespace RKMES.Models
{ // essa é uma tabela intermediaria das entidades Grupo_Permissao e Permissao
public class Grupo_Permissao_Permissao
{
public int Id { get; set; }
public int Grupo_PermissaoId { get; set; }
public int PermissaoId { get; set; }
public virtual Grupo_Permissao Grupo_Permissao { get; set; }
public virtual Permissao Permissao { get; set; }
}
}
What am I doing wrong?
For your issue, it is caused by ValidateAntiForgeryToken. which will check whether the request contains RequestVerificationToken header.
For a quick test, you could remove [ValidateAntiForgeryToken] from Controller.
For a recommended way, you need to attach the anti forgery token like
<script type="text/javascript">
$(document).ready(function(){
var Group = {
GroupId: 1,
GroupName: "My Group Name"
};
AjaxPost("/Groups/AddGroup", Group).done(function () {
GetGroups();
});
});
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
function AjaxPost(url, data) {
return $.ajax({
type: "post",
contentType: "application/json;charset=utf-8",
dataType: "json",
responseType: "json",
url: url,
headers: {
"RequestVerificationToken": gettoken()
},
data: JSON.stringify(data)
});
}
</script>
I have a Kendo Grid where I bind it dynamically to a JSON object.
In the generateColumns function, I want to call the getKendoColor function. However, I need to pass the column cell value. In the code below I forced in 'RED' to show how it should work.
How do I pass in the column value to this getKendoColor function?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Kendo UI Snippet</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.mobile.all.min.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.3.913/js/kendo.all.min.js"></script>
</head>
<body>
<div id="grid" style="width:1000px;"></div>
<script>
var isDateField =[];
var isTaskField =[];
$.ajax({
url: "http://www.mocky.io/v2/59c4dd1e4000005400b25ba7",
dataType: "jsonp",
success: function(result) {
generateGrid(result);
}
});
function generateGrid(response) {
var model = generateModel(response);
var columns = generateColumns(response);
var grid = $("#grid").kendoGrid({
dataSource: {
transport:{
read: function(options){
options.success(response.Table);
}
},
pageSize: 5,
schema: {
model: model
}
},
columns: columns,
pageable: true,
editable:false
});
}
function generateColumns(response) {
var columnNames = response["columns"];
return columnNames.map(function (name) {
if (isTaskField[name]) {
return { field: name, template: '#= getKendoColor("RED") #', format: (isDateField[name] ? "{0:D}" : "") };
}
else
return { field: name, format: (isDateField[name] ? "{0:D}" : "") };
})
}
function generateModel(response) {
var sampleDataItem = response["Table"][0];
var model = {};
var fields = {};
for (var property in sampleDataItem) {
var itemValue = sampleDataItem[property];
if (property.indexOf("ID") !== -1) {
model["id"] = property;
}
var propType = typeof sampleDataItem[property];
if (propType === "number") {
fields[property] = {
type: "number",
validation: {
required: true
}
};
if (model.id === property) {
fields[property].editable = false;
fields[property].validation.required = false;
}
} else if (propType === "boolean") {
fields[property] = {
type: "boolean"
};
} else if (propType === "string") {
var parsedDate = kendo.parseDate(sampleDataItem[property]);
if (parsedDate) {
fields[property] = {
type: "date",
validation: {
required: true
}
};
isDateField[property] = true;
} else {
fields[property] = {
validation: {
required: true
}
};
if ((property !== "Entity") && (property !== "Period") && (property !== "Level"))
{
isTaskField[property] = true;
}
}
} else {
fields[property] = {
validation: {
required: true
}
};
}
}
model.fields = fields;
return model;
}
function getKendoColor(OverallStatus) {
OverallStatus = OverallStatus.toUpperCase();
//alert(OverallStatus);
var htmlRed = kendo.format('<div class="text-center"><div style="color:red"> <i class="fa fa-circle fa-lg"></i> </div> </div>');
var htmlGreen = kendo.format('<div class="text-center"><div style="color:green"> <i class="fa fa-circle fa-lg"></i> </div> </div>');
var htmlOrange = kendo.format('<div class="text-center"><div style="color:orange"> <i class="fa fa-circle fa-lg"></i> </div> </div>');
var htmlYellow = kendo.format('<div class="text-center"><div style="color:yellow"> <i class="fa fa-circle fa-lg"></i> </div> </div>');
switch (OverallStatus) {
case "RED":
return htmlRed;
case "GREEN":
return htmlGreen;
case "ORANGE":
return htmlOrange;
case "YELLOW":
return htmlYellow;
case "CREATED":
return htmlRed;
case "APPROVED":
return htmlGreen;
}
}
</script>
</body>
</html>
https://dojo.telerik.com/AgALaK/2
You can set the template itself as a function and in your case, a slight change to getKendoColor will do the trick:
function getColumnTemplate(dataItem) {
var OverallStatus = dataItem.OverallStatus.toUpperCase();
//All the rest of your getKendoColor function
return someHTML;
}
Then just use this function as the template.
return columnNames.map(function (name) {
if (isTaskField[name]) {
return { field: name, template: getColumnTemplate, format: (isDateField[name] ? "{0:D}" : "") };
}
else
return { field: name, format: (isDateField[name] ? "{0:D}" : "") };
})
I am trying to get data from controller to view using ajax but not successfull. Following is my code this is working fine but not getting data. Please help and correct me if i missed something in my code.
Following is my code.
#model MvcAppLearn.Models.Student
<!DOCTYPE html>
<html lang="en">
<head>
<title>This is tile</title>
</head>
<body>
#using (Html.BeginForm("Index", "popup", FormMethod.Get, new { id = "myform" }))
{
<p>
Find by name: #Html.TextBox("SearchString")
<button id="model-opener">Open dialog</button>
</p>
<div id="dialog-model" title="This is title">
<p>
#Html.TextBoxFor(item => item.FirstName, new { id = "ffirst" })<br />
#Html.TextBoxFor(item => item.LastName, new { id = "llast" })<br />
</p>
</div>
}
</body>
</html>
#section script
{
<script>
$(function () {
$("#dialog-model").dialog({
autoOpen: false,
height: 300,
width: 340,
model: true,
show: {
effect: "shake",
duration: 100
},
});
$("#model-opener").click(function (e) {
e.preventDefault();
var txtFirstName = $('#ffirst');
var txtLastName = $('#llast');
var txtSearch = $('#SearchString');
$.ajax({
url: '/popup/Index',
type: 'GET',
data: {
StudentId: txtSearch.val()
},
success: function (data) {
txtFirstName.val(data.FirstName); //HERE IS THE PROBLEM IN GETTING VALUE
txtLastName.val(data.LastName); //HERE IS THE PROBLEM IN GETTING VALUE
$("#dialog-model").dialog("open");
},
error: function () {
alert("Oh noes");
}
});
});
});
</script>
}
Below is my controller
public ActionResult Index(int? StudentId)
{
if (StudentId == null)
{
StudentId = 2;
return View();
}
using (var db = new StdContext())
{
Student std = new Student();
std = db.Students.Where(m => m.StudentId == StudentId).Single();
return View(std);
}
}
You're not returning data, you're returning a view:
return View(std);
If you just want to return the data of the Student object to be consumed by JavaScript code then you probably just want to return it as JSON data:
return Json(std);
I want to transfer model data from one View to another View (in a dialog) using Ajax.Actionlink were i am getting null values on Post Action
This is my View
#using (Ajax.BeginForm("", new AjaxOptions { }))
{
for (int i = 0; i < Model.city.Count; i++)
{
<div class="editor">
<p>
#Html.CheckBoxFor(model => model.city[i].IsSelected, new { id = "check-box-1" })
#Html.HiddenFor(model => model.city[i].Id)
#Ajax.ActionLink(Model.city[i].Name, "PopUp", "Home",
new
{
#class = "openDialog",
data_dialog_id = "emailDialog",
data_dialog_title = "Cities List",
},
new AjaxOptions
{
HttpMethod = "POST"
})
#Html.HiddenFor(model => model.city[i].Name)
</p>
</div>
}
}
On using Ajax.Actionlink i am creating a dialog using ajax scripting
My controller class for this View is
public ActionResult Data()
{
var cities = new City[] {
new City { Id = 1, Name = "Mexico" ,IsSelected=true},
new City { Id = 2, Name = "NewJersey",IsSelected=true },
new City { Id = 3, Name = "Washington" },
new City { Id = 4, Name = "IIlinois" },
new City { Id = 5, Name = "Iton" ,IsSelected=true}
};
var model = new Citylist { city = cities.ToList() };
//this.Session["citylist"] = model;
return PartialView(model);
}
another View for displaying Post action data is
#model AjaxFormApp.Models.Citylist
#{
ViewBag.Title = "PopUp";
}
<h2>
PopUp</h2>
<script type="text/javascript">
$(function () {
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
var checkedAtLeastOne = false;
$('input[id="check-box-2"]').each(function () {
if ($(this).is(":checked")) {
checkedAtLeastOne = true;
// alert(checkedAtLeastOne);
}
});
if (checkedAtLeastOne == true) {
// alert("Test");
$('#div1').show();
$(".dialog").dialog("close");
}
else {
// alert("NotSelected");
$('#div1').hide();
$('#popUp').html(result);
$('#popUp').dialog({
open: function () { $(".ui-dialog-titlebar-close").hide(); },
buttons: {
"OK": function () {
$(this).dialog("close");
}
}
});
}
}
});
return false;
});
});
</script>
<div style="display: none" id="div1">
<h4>
Your selected item is:
</h4>
</div>
#using (Ajax.BeginForm(new AjaxOptions { }))
{
for (int i = 0; i < Model.city.Count; i++)
{
<div class="editor">
<p>
#Html.CheckBoxFor(model => model.city[i].IsSelected,new { id = "check-box-2" })
#Html.HiddenFor(model => model.city[i].Id)
#Html.LabelFor(model => model.city[i].Name, Model.city[i].Name)
#Html.HiddenFor(model => model.city[i].Name)
</p>
</div>
}
<input type="submit" value="OK" id="opener" />
}
#*PopUp for Alert if atleast one checkbox is not checked*#
<div id="popUp">
</div>
and my post controller action result class is
[HttpPost]
public ActionResult PopUp(Citylist model)
{
if (Request.IsAjaxRequest())
{
//var model= this.Session["citylist"];
return PartialView("PopUp",model);
}
return View();
}
My model class is
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class Citylist
{
public IList<City> city { get; set; }
}
You are calling Popup action from actionlink. Instead you should place submit button out of for loop. And give your form right action parameters