I'm stuck trying to kick out bootstrap treeview (https://github.com/jonmiles/bootstrap-treeview). I am new at this.
I think I do everything right, but it does not work for me.
I think I put everything I needed to understand the problem.
Thanks for the help.
I have the following code taken from another question, but it does not work.
In ASP NET:
private static List<RoleViewModel> roles = new List<RoleViewModel>();
public static RoleViewModel ChildrenOf(RoleViewModel rol)
{
foreach (RoleViewModel child in roles.Where(x => x.ParentId == rol.Id))
{
rol.ChildRoles.Add(ChildrenOf(child));
}
return rol;
}
public ActionResult GetProgresoGlobalTreeData()
{
roles = new List<RoleViewModel>
{
new RoleViewModel { Id = 1, ParentId = null, text = "ED" },
new RoleViewModel { Id = 2, ParentId = 1, text = "CPD" },
new RoleViewModel { Id = 3, ParentId = 2 ,text = "Center Manager" },
new RoleViewModel { Id = 4 , ParentId = 3, text = "Manager" },
new RoleViewModel { Id = 5 , ParentId = 4, text = "Tech Head" },
new RoleViewModel { Id = 6 , ParentId = 5, text = "Individual" }
};
RoleViewModel role = new RoleViewModel();
role = ChildrenOf(roles[0]);
var json = JsonConvert.SerializeObject(new[] { role });
JsonResult ret = Json(json, JsonRequestBehavior.AllowGet);
return ret;
}
Html:
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="panel panel-primary">
<div class="panel-heading">
#MQWEB.Resources.Textos.InformesDeProgreso
</div>
</div>
<div id="tree">
</div>
#section scripts
{
<script>
$(document).ready(function () {
$('#tree').treeview({ data: getTree() });
});
function getTree() {
var tree = null;
$.getJSON('#Url.Action("GetProgresoGlobalTreeData")', function (result) {
var tree = JSON.parse(result);
});
return tree;
}
</script>
}
In layout I have everything I need to make it work.
<head>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-theme.min.css" rel="stylesheet" />
<link rel="stylesheet" href="~/Content/font-awesome.min.css">
<link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet">
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />
<link href="~/Content/jquery-ui-timepicker-addon.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-select.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-treeview.min.css" rel="stylesheet" />
</head>
<body>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/notify.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/modernizr-2.8.3.js"></script>
<script src="~/Scripts/pdfobject.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.min.js"></script>
<script src="~/Scripts/jquery-ui-timepicker-addon.min.js"></script>
<script src="~/Scripts/bootstrap-select.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/datetime-moment.js"></script>
<script src="~/Scripts/bootstrap-treeview.min.js"></script>
</body>
</html>
#RenderSection("scripts", required: false)
This is the data that browser display (json returned) after GetProgresoGlobalTreeData() is called:
"[{\"text\":\"ED\",\"nodes\":[{\"text\":\"CPD\",\"nodes\":[{\"text\":\"Center
Manager\",\"nodes\":[{\"text\":\"Manager\",\"nodes\":[{\"text\":\"Tech
Head\",\"nodes\":[{\"text\":\"Individual\",\"nodes\":[]}]}]}]}]}]}]"
I forgot the class, I'm using Newtonsoft.Json:
public class RoleViewModel
{
public RoleViewModel()
{
this.ChildRoles = new List<RoleViewModel>();
}
public string text { get; set; }
//public string icon { get { return "glyphicon glyphicon-user"; } }
[JsonIgnore]
public int Id { get; set; }
[JsonIgnore]
public int? ParentId { get; set; }
[JsonProperty("nodes")]
public List<RoleViewModel> ChildRoles { get; set; }
}
You do not need to serialize the object, remove the following:
var json = JsonConvert.SerializeObject(new[] { role });
Do this instead:
return Json(new[] { role }, JsonRequestBehavior.AllowGet);
EDIT:
I forgot to mention that you don't need to parse the return in JS and simply return the Json object receveid from the controller
function getTree() {
var tree = null;
$.getJSON('#Url.Action("GetProgresoGlobalTreeData")', function (result) {
tree = result
});
return tree;
}
Thanks to everyone for your ideas.
The solution was to change the js to:
$(document).ready(function () {
$.getJSON('#Url.Action("GetProgresoGlobalTreeData")', function (result) {
$('#tree').treeview({ data: result });
});
});
and it works!
Thanks
Related
I have 4 Views(index view, navigation bar view, Partial view1, partialview2) in One controller
I'd like to switch The Partial View in index view when click navbaritem.
I set LeftPanelPartial in #section.
If I click navbar item, switch ProdFViewPartial() to ProdJViewPartial()
How Can I Get This.
check my code
Controller
namespace DXWMes.Controllers
{
public class ProdController : Controller
{
// GET: Prod
public ActionResult Index()
{
ProdRepository ProdRepo = new ProdRepository();
return View(ProdRepo.GetProdFData("1", "F11", "20220901"));
}
public ActionResult ProdFViewPartial()
{
ProdRepository ProdRepo = new ProdRepository();
return PartialView("ProdFViewPartial",ProdRepo.GetProdFData("1", "F11", "20220901"));
}
public ActionResult ProdJViewPartial()
{
ProdRepository ProdRepo = new ProdRepository();
return View("ProdJViewPartial", ProdRepo.GetProdJData("1", "20220901"));
}
VIEW - Index
#model List<DXWMes.Model.ProdFModel>
#{
ViewBag.Title = "Prod";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Head {
<link rel="stylesheet" type="text/css" href="#Url.Content("~/Content/ProdView.css")" />
<script type="text/javascript" src="#Url.Content("~/Content/ProdView.js")"></script>
}
#section LeftPanelContent {
#Html.Partial("LeftPanelPartial")
}
#section RightPanelContent {
<div class="settings-content">
<h2>Settings</h2>
<p>Place your content here</p>
</div>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.Partial("ProdFViewPartial")
}
<div id="detailView"> </div>
View - LeftPanelPartial
<h3 class="leftpanel-section section-caption">Production</h3>
#Html.DevExpress().NavBar(navBarSettings =>
{
navBarSettings.Name = "NavBar";
navBarSettings.AllowSelectItem = true;
navBarSettings.ShowGroupHeaders = false;
navBarSettings.Width = Unit.Percentage(100);
navBarSettings.ControlStyle.CssClass = "ProdNavbar";
navBarSettings.Styles.Item.CssClass = "item";
navBarSettings.Groups.Add(group =>
{
group.Items.Add(item =>
{
item.Name = "ProdE1";
item.Selected = true;
});
group.Items.Add(item =>
{
item.Name = "ProdE5";
});
group.Items.Add(item =>
{
item.Name = "ProdF";
});
group.Items.Add(item =>
{
item.Name = "ProdJ";
});
});
navBarSettings.ClientSideEvents.ItemClick = "onProdNavBarItemClick";
}).GetHtml()
JS
(function () {
var selectedIds;
var itemids;
function onProdInit(s, e) {
AddAdjustmentDelegate(adjustProd);
updateToolbarButtonsState();
}
function onProdSelectionChanged(s, e) {
updateToolbarButtonsState();
}
function adjustProd() {
Prod.AdjustControl();
}
function updateToolbarButtonsState() {
var enabled = Prod.GetSelectedRowCount() > 0;
pageToolbar.GetItemByName("Export").SetEnabled(enabled);
}
function onProdNavBarItemClick(s, e)
{
$.ajax({
Url: ' #Url.Action(e.item.name, "Prod")',
type: 'GET',
}).done(funtion(result) {
if(result.redirectTo)
$('#detailView').html(result);
}).fail(function (jqXHR, exception) {
showError(jqXHR);
})
//switch (e.item.name) {
// case "ProdJ"
I have a view where I am trying to implement the auto populate the text box/drop down field. I am using a list which I query on.
I am following this example http://www.dotnetqueries.com/Article/159/how-to-implement-select2-with-ajax-and-json-in-asp-net-mvc , break point does not even hit the method in my controller. so is there something wrong with the way I set this up or the way the action result method is called in controller.
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using TestSelect2.Models;
using Controller = Microsoft.AspNetCore.Mvc.Controller;
namespace TestSelect2.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[Microsoft.AspNetCore.Mvc.HttpPost]
[Microsoft.AspNetCore.Mvc.Route("/home/account-list")]
public Microsoft.AspNetCore.Mvc.ActionResult GetAccounts(string q)
{
List<Account> accounts = new List<Account>();
// Add parts to the list.
accounts.Add(new Account() { Id = 1, AccountNumber = "MVP1" });
accounts.Add(new Account() { Id = 1, AccountNumber = "MVP11" });
accounts.Add(new Account() { Id = 1, AccountNumber = "ABC2" });
accounts.Add(new Account() { Id = 1, AccountNumber = "ABC3" });
accounts.Add(new Account() { Id = 1, AccountNumber = "XYZ3" });
accounts.Add(new Account() { Id = 1, AccountNumber = "XYZ4" });
if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
{
accounts = accounts.Where(x => x.AccountNumber.ToLower().StartsWith(q.ToLower())).ToList();
}
return Json(new { items = accounts }, JsonRequestBehavior.AllowGet);
}
}
}
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Select2 DEMO</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script>
$(document).ready(function () {
$(".accountSelect").select2({
ajax: {
url: '/home/account-list',
width: 'resolve',
data: function (params) {
return {
q: params.term// search term
};
},
processResults: function (data) {
return {
results: data.items
};
},
minimumInputLength: 2,
width: 'resolve'
}
});
});
</script>
<style>
body {
margin: auto;
width: 600px;
padding: 50px;
}
.accountSelect {
width: 400px;
}
</style>
</head>
<body>
<form method="post">
<select class="accountSelect"></select>
</form>
</body>
</html>
Remove the [HttpPost] attribute on GetAccounts action. Since the ajax makes a get request.And the tutorial you follow is for asp.net but not asp.net core, there is no JsonRequestBehavior.
Note: select2model must with id and text two properties, otherwise, it can't be recognized. Change your Account model like below:
public class Account
{
public int Id { get; set; }
public string Text { get; set; }
}
And the controller action, make sure the id can't be the same.
[Route("/home/account-list")]
public IActionResult GetAccounts(string q)
{
List<Account> accounts = new List<Account>();
// Add parts to the list.
accounts.Add(new Account() { Id = 1, Text = "MVP1" });
accounts.Add(new Account() { Id = 2, Text = "MVP11" });
accounts.Add(new Account() { Id = 3, Text = "ABC2" });
accounts.Add(new Account() { Id = 4, Text = "ABC3" });
accounts.Add(new Account() { Id = 5, Text = "XYZ3" });
accounts.Add(new Account() { Id = 6, Text = "XYZ4" });
if (!(string.IsNullOrEmpty(q) || string.IsNullOrWhiteSpace(q)))
{
accounts = accounts.Where(x => x.Text.ToLower().StartsWith(q.ToLower())).ToList();
}
return Json(new { items = accounts });
}
View and Scripts:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Select2 DEMO</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script>
$(document).ready(function () {
$(".accountSelect").select2({
minimumInputLength: 2,
ajax: {
url: '/home/account-list',
data: function (params) {
return {
q: params.term// search term
};
},
processResults: function (data) {
return {
results: data.items
}
},
}
});
});
</script>
<style>
body {
margin: auto;
width: 600px;
padding: 50px;
}
.accountSelect {
width: 400px;
}
</style>
</head>
<body>
<form method="post">
<select class="accountSelect"></select>
</form>
</body>
</html>
Result:
You may try as below:
//1. Action Method Which Returns the data.
public ActionResult GetSelect2Data(string query)
{
//In Realtime This should come from the Database
List<DropDownItem> collection = new List<DropDownItem>() {
new DropDownItem(){ Value = 1, Text = "Switzerland"},
new DropDownItem(){ Value = 2, Text = "Canada"},
new DropDownItem(){ Value = 3, Text = "Japan"},
new DropDownItem(){ Value = 4, Text = "Germany"},
new DropDownItem(){ Value = 5, Text = "Australia"},
new DropDownItem(){ Value = 6, Text = "United Kingdom"},
new DropDownItem(){ Value = 7, Text = "United States"},
new DropDownItem(){ Value = 8, Text = "Sweden"},
new DropDownItem(){ Value = 9, Text = "India"},
new DropDownItem(){ Value = 10, Text = "Russia"},
};
var searchResult = from c in collection
where c.Text.Contains(query,
StringComparison.CurrentCultureIgnoreCase)
select c;
return Json(searchResult.ToList());
}
///2. JS Method which binds any HTML Select as Select2 or Smart Select.
///In the User Interface (.cshtml file)You may define a framework JS Function as which could be used anywhere
function registerSelect2(dropDownSelector, ajaxUrl) {
$(dropDownSelector).select2({
ajax: {
url: ajaxUrl,
dataType: 'json',
delay: 10,
type: 'GET',
data: function (params) {
return {
query: params.term, // search term
};
}
, processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id: item.value,
text: item.text,
};
})
};
},
cache: true,
},
minimumInputLength: 3,
allowHtml: true,
allowClear: true
});
}
//3. Invoke the JS Function to make any particular Select a Select2.
$(function () {
//Just you need to pass the Selector of your control and the Ajax Url from which data has to be loaded
registerSelect2("#ddlSelect2", "/user/GetSelect2Data");
});
//This is the Simple Select which's made a Select2 Control. Paste it somewhere in the UI
<select id="ddlSelect2"></select>
$(function() {
var model = {
currentCat: null,
cats: [{
name: "Felix",
clickCounter: 0,
srcImage: "cat0.jpg"
},
{
name: "Lucas",
clickCounter: 0,
srcImage: "cat1.jpg"
},
{
name: "Martin",
clickCounter: 0,
srcImage: "cat2.jpg"
},
{
name: "Pedro",
clickCounter: 0,
srcImage: "cat3.jpg"
}
]
};
var octopus = {
init: function() {
indexView.init();
displayView.init();
},
getCats: function() {
return model.cats;
},
getCurrentCat: function() {
return model.currentCat;
},
setCurrentCat: function(cat) {
model.currentCat = cat;
},
updateClickCounter: function() {
model.currentCat.clickCounter++;
displayView.render();
}
};
var displayView = {
init: function() {
this.imgSection = document.getElementById("imageSection");
this.catImg = document.getElementById("cat-img");
this.catName = document.getElementById("cat-name");
this.catCounter = document.getElementById("cat-counter");
this.catImg.addEventListener("click", function() {
octopus.updateClickCounter();
})
this.render()
},
render: function() {
var cat = octopus.getCurrentCat();
this.catName.textContent = cat.name;
this.catCounter.textContent = cat.clickCounter;
this.catImg.src = cat.srcImage;
}
};
var indexView = {
init: function() {
this.list = $("#list")
this.render();
},
render: function() {
cats = octopus.getCats();
for (i = 0; i < cats.length; i++) {
cat = cats[i];
listElement = document.createElement("li");
listElement.textContent = cat.name;
listElement.addEventListener("click", (function(copyCat) {
octopus.setCurrentCat(copyCat);
displayView.render();
})(cat));
};
}
};
octopus.init();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cat clicker</title>
<link rel="stylesheet" href="css/cat.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css" type="text/css" />
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/cat.js"></script>
<h1 id="header"> Gatitos! </h1>
<div id="catIndex">
<h2 id="indexTitle">Index</h2>
<ul id="list">
<!-- here we have the index with the cats names -->
</ul>
</div>
<div id="imageSection">
<h2 id="cat-name"></h2>
<div id="cat-counter"></div>
<img src="" id="cat-img">
</div>
</body>
</html>
in the displayView object, I can only acces the html elements that I got with getElementById inside the method they were initialized in (I can acces catImg when I add the event listener in the init method). The problem comes when I try to acces those elements in the render method. When you run this it returns undefined when you call all the elements from the init method (this.catImg, this.catName and this.catCounter). Why does it return undefined?
you have to bind 'this' to your event handler, check out Javascript scope addEventListener and this on how to scope this to your event listener.
Was receiving this error:
An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
Additional information: DataBinding: 'Final.Models.Hello' does not contain a property with the name '700'.
I looked through google for some answers, but I still feel lost.
Model class:
public Hello () {
db = new ExtensionDBEntities();
}
public List<Hello> getID()
{
var que = (from rel in db.Table1
select new Hello
{
ID = rel.ID
}).ToList();
return que;
}
public List<Hello> getStuff()
{
var que = (from wre in db.View
select new Hello
{
ID = wre.ID,
Summary = wre.Summary,
Description = wre.Description
}
}
getHello() is the same exact method as the getStuff(), just accepts a string ID parameter.
Controller class:
public ActionResult Index()
{
var model = test.getStuff();
ViewBag.Releases = new SelectList(test.getID(), "", "ID");
ViewBag.Managers = new SelectList(test.getManagers(), "", "Managers");
return View("");
}
[HttpPost]
public ActionResult Selection()
{
string selectedId = Request["IDText"].ToString();
string Managers = Request["ManagersText"].ToString();
var model = test.getStuff();
ViewBag.Releases = new SelectList(test.getID(), selectedId, "ID");
ViewBag.Managers = new SelectList(test.getManagers(), Managers, "Managers");
var que = test.getHello(selectedId, Managers);
return View(que);
}
Index View Class:
$(document).ready(function () {
$("#Releases").on("change", function () {
var value = $('#Releases :selected').text()
$("#IDText").val(value);
});
$("#Managers").on("change", function () {
var value = $('#Managers :selected').text()
$("#ManagersText").val(value);
});
});
#using (Html.BeginForm("Selection", "Sample", FormMethod.Post))
{
<div class="container" id='div_release'>
#Html.DropDownList("Releases", ViewBag.Releases as SelectList)
#Html.DropDownList("Managers", ViewBag.Managers as SelectList)
#Html.Hidden("IDText", "")
#Html.Hidden("ManagersText", "")
<input type="submit" name="Submit" id="btnUploadData" class="btn btn-primary" value="Upload" />
</div>
}
Selection View Class:
<div class="container">
<table id="myTable" align="left">
<tr>
<th>#Html.DisplayNameFor(model => model.ID)</th>
<th>#Html.DisplayNameFor(model => model.Summary)</th>
<th>#Html.DisplayNameFor(model => model.Description)</th>
</tr>
#foreach (var item in Model)
{
<tr id="Home">
<td>#Html.DisplayFor(x => item.ID)</td>
<td>#Html.DisplayFor(x => item.Summary)</td>
<td>#Html.DisplayFor(x => item.Description)</td>
</tr>
}
$(document).ready(function () {
$("#Releases").on("change", function () {
var value = $('#Releases :selected').text()
$("#IDText").val(value);
});
$("#Managers").on("change", function () {
var value = $('#Managers :selected').text()
$("#ManagersText").val(value);
});
});
#using (Html.BeginForm("Selection", "Sample", FormMethod.Post))
{
<div class="container" id='div_release'>
#Html.DropDownList("Releases", ViewBag.Releases as SelectList) // Getting the error here....
#Html.DropDownList("Managers", ViewBag.Managers as SelectList)
#Html.Hidden("IDText", "")
#Html.Hidden("ManagersText", "")
<input type="submit" name="Submit" id="btnUploadData" class="btn btn-primary" value="Submit" />
</div>
}
</table>
</div>
The error occurs in the Selection View Class. The View classes are almost identical, the only difference being is the data being displayed in the Selection View Class based on the selected value from the drop down list.
Here is a link to a fiddle that combines the views into one: https://dotnetfiddle.net/5uCKhI
This should help you. Please let me know if there is anything else.
Controller/Model
public class caitlinpRealViewModel
{
public List<SelectListItem> IDList { get; set; }
public string selectedId { get; set; }
public List<SelectListItem> ManagerList { get; set; }
public string selectedManager { get; set; }
}
public class HomeController : Controller
{
public caitlinpRealViewModel SetupViewModel(caitlinpRealViewModel vm)
{
caitlinpRealViewModel viewModel = new caitlinpRealViewModel();
if (vm != null)
{
viewModel.selectedId = vm.selectedId;
}
else
{
viewModel.selectedId = "1";
}
SelectListItem listItem = new SelectListItem() { Text = "1", Value = "1" };
SelectListItem listItem2 = new SelectListItem() { Text = "2", Value = "2" };
List<SelectListItem> list = new List<SelectListItem>();
list.Add(listItem);
list.Add(listItem2);
if (vm != null)
{
viewModel.selectedManager = vm.selectedManager;
}
else
{
viewModel.selectedManager = "1";
}
SelectListItem listItem3 = new SelectListItem() { Text = "aManager", Value = "1" };
SelectListItem listItem4 = new SelectListItem() { Text = "bManager", Value = "2" };
List<SelectListItem> list2 = new List<SelectListItem>();
list2.Add(listItem3);
list2.Add(listItem4);
viewModel.IDList = list;
viewModel.ManagerList = list2;
return viewModel;
}
[HttpPost]
public ActionResult Selection(caitlinpRealViewModel vm)
{
caitlinpRealViewModel viewModel = SetupViewModel(vm);
return View(viewModel);
}
public ActionResult Tut135()
{
caitlinpRealViewModel viewModel = SetupViewModel(null);
return View(viewModel);
}
View 1
#model Testy20161006.Controllers.caitlinpRealViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut135</title>
</head>
<body>
#using (Html.BeginForm("Selection", "Home", FormMethod.Post))
{
<div class="container" id='div_release'>
#Html.DropDownListFor(m => m.selectedId, new SelectList(Model.IDList, "Value", "Text"))
#Html.DropDownListFor(m => m.selectedManager, new SelectList(Model.ManagerList, "Value", "Text"))
<input type="submit" name="Submit" id="btnUploadData" class="btn btn-primary" value="Upload" />
</div>
}
</body>
</html>
View 2 (Selection)
#model Testy20161006.Controllers.caitlinpRealViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Selection</title>
</head>
<body>
<div class="container">
<table id="myTable" align="left">
#using (Html.BeginForm("Selection", "Home", FormMethod.Post))
{
<div class="container" id='div_release'>
#Html.DropDownListFor(m => m.selectedId, new SelectList(Model.IDList, "Value", "Text"))
#Html.DropDownListFor(m => m.selectedManager, new SelectList(Model.ManagerList, "Value", "Text"))
<input type="submit" name="Submit" id="btnUploadData" class="btn btn-primary" value="Submit" />
</div>
}
</table>
</div>
</body>
</html>
Hi I am trying to implement Auto Complete Text Box using "typeahead.js" something like http://sriniavatar.com/bootstrap-typeahead-in-asp-net-mvc/ in my MVC Project
My Script are bellow
<script type="text/javascript">
var substringMatcher = function (strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function (i, str) {
if (substrRegex.employees(str)) {
matches.push(str);
}
});
cb(matches);
};
};
$.post('/Employee/TagSearch', null, function (data) {
var employees = data;
$('#sriniavatar').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'employees',
displayKey: 'value',
source: substringMatcher(employees)
});
});
And My Employee Controller's TagSearch Method is given bellow
[HttpPost]
public ActionResult TagSearch(string term)
{
DataAccess db = new DataAccess();
var employees = db.GetEmployeesName().ToList();
//if (!String.IsNullOrEmpty(term))
//{
// employees = employees.Where(e => e.Surname.Contains(term.Trim())
// || e.ForeName.Contains(term.Trim())
// || e.Win_UserName.Contains(term.Trim())
// ).ToList();
//}
return Json(employees, JsonRequestBehavior.AllowGet);
}
Now **Problem is that when I am running programme its showing following Error *"Unhandled exception at line 95, column 21 in http://localhost:57512/Employee/ViewEmployees
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'employees'"***
even though I have referenced following the scripts in my project
<link href="~/Content/typeahead.css" rel="stylesheet" /> <script "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script> <script src="~/Scripts/typeahead.js"></script> <br/>...Page Contents...<br>
<script src="~/Scripts/typeahead.mvc.model.js"></script>
#RenderSection("scripts", required: false)
I do not know of any JavaScript that has an employees method with regExp
if (substrRegex.employees(str)) {
^^^^^^^^^
I believe you want test
if (substrRegex.test(str)) {