Single or many items can be selected by users in the ListView component. An API is used to get selected items from the
list items. This is called as the
getSelectedItems
method.
getSelectedItems
method
This is used to get the details of the currently selected item from the list items. It returns the
SelectedItem
|
SelectedCollection
The getSelectedItems
method returns the following items from the selected list items.
Return type | Purpose |
---|---|
text | Returns the text of selected item lists |
data | Returns the whole data of selected list items, i.e., returns the fields data of selected li. |
item | Returns the collections of list items |
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource).Fields(new ListViewFieldSettings { Text = "text", Id="id"}).ShowCheckBox(true).Render()
<div id="text">
@Html.EJS().Button("btn").Content("Get selected Items").Render()
<table id="val"></table>
</div>
<style>
#text {
margin-left: 10px;
margin-top: 20px;
}
#element {
max-width: 350px;
margin: auto;
margin-top: 10px;
display: block;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
<script>
document.getElementById('btn').addEventListener('click', () => {
var selecteditem = document.getElementById('element').ej2_instances[0].getSelectedItems();
var data = document.getElementById('val');
data.innerHTML = "";
var row1 = document.createElement('tr');
var header1 = document.createElement('th');
header1.innerHTML = 'Text';
row1.appendChild(header1);
var header2 = document.createElement('th');
header2.innerHTML = 'Id';
row1.appendChild(header2);
document.getElementById('val').appendChild(row1);
for (var i= 0; i < (selecteditem["data"]).length; i++) {
var row2 = document.createElement('tr');
row2.setAttribute("id", i.toString());
var data1 = document.createElement('td');
data1.innerHTML = selecteditem["text"][i];
row2.appendChild(data1);
var data2 = document.createElement('td');
data2.innerHTML = (selecteditem["data"])[i].id.toString();
row2.appendChild(data2);
document.getElementById('val').appendChild(row2);
}
});
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
text = "Hennessey Venom",
id = "list-01"
}); listdata.Add(new
{
text = "Bugatti Chiron",
id = "list-02"
}); listdata.Add(new
{
text = "Bugatti Veyron Super Sport",
id = "list-03"
}); listdata.Add(new
{
text = "SSC Ultimate Aero",
id = "list-04"
}); listdata.Add(new
{
text = "Koenigsegg CCR",
id = "list-05"
}); listdata.Add(new
{
text = "McLaren F1",
id = "list-06"
}); listdata.Add(new
{
text = "Aston Martin One- 77",
id = "list-07"
}); listdata.Add(new
{
text = "Jaguar XJ220",
id = "list-08"
});
ViewBag.dataSource = listdata;
return View();
}
}
}
The Syncfusion Essential JS2 components are desktop and mobile-friendly. So, you can use Syncfusion components in both modes. The component templates are not always fixed. Applications may need to load various templates depending upon the device.
In the ListView component, template support is being used. In some cases, the component wrapper is always responsive across all devices, but the template contents are dynamically changed with unspecified (sample side) dimensions. CSS customization is also needed in sample-side to align template content responsively in both mobile and desktop modes. Here, two templates have been loaded for mobile and desktop modes. To check the device mode, a browser module has been imported from the ej2-base package.
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@{
var wintemplate = "";
var width = "";
var mob_template = "<div class='settings'>"
+ "<div id='postContainer'><div id='postImg'> "
+ "<img src=${image} /></div>"
+ "<div id='content'> "
+ "<div id='info'> "
+ "<div id='logo'> <div id= 'share'> "
+ "<span class='share'></span> </div> <div id='comments'> <span class='comments'></span> </div>"
+ "<div id='bookmark'> <span class='bookmark'></span> </div></div></div>"
+ "<div class='name'>${Name}</div>"
+ "<div class='description'>${content}</div>"
+ "<div class='timeStamp'>${timeStamp} </div>"
+ "</div>";
var template = "<div class='settings'><div id='postContainer'><div id='postImg'><img src=${image} /></div><div id='content'>"
+ "<div class='name'>${Name}</div><div class='description'>${content}</div><div id='info'>"
+ "<div id='logo'><div id='share'><span class='share'></span>"
+ "</div> <div id='comments'> <span class='comments'></span> </div>"
+ "<div id='bookmark'> <span class='bookmark'></span> </div></div>"
+ "<div class='timeStamp'>${timeStamp} </div></div></div>";
if (Request.Browser.IsMobileDevice)
{
width = "350px";
wintemplate = mob_template;
}
else
{
wintemplate = template;
}
}
@Html.EJS().ListView("List").DataSource((IEnumerable<object>)ViewBag.dataSource).HeaderTitle("Syncfusion Blog").ShowHeader(true).Width(width).Template(wintemplate).Render()
<style>
#List img {
height: 70px;
width: 70px;
border-radius: 50%;
border: 1px solid #ccc;
}
#List {
display: block;
max-width: 400px;
margin: auto;
border: 1px solid;
border-color: #c3c3c3;
border-color: rgba(0, 0, 0, 0.12);
}
#List .settings {
height: 170px;
line-height: 70px;
margin-left: 16px;
margin-right: 16px;
}
#List .e-list-item {
height: 170px;
line-height: 70px;
padding: 0;
cursor: pointer;
border-bottom: 0.8px solid #ddd;
}
#time {
line-height: 23px;
margin-top: 13px;
padding-left: 10px;
width: 191px;
}
#img {
float: left;
padding-top: 6px;
padding-left: 0;
padding-right: 20px;
}
#info {
padding-top: 3px;
}
#List .e-list-header {
color: white;
height: 57px;
background-color: #56697f;
padding-left: 15px;
position: relative;
top: -1px;
}
.bootstrap #List .e-list-header .e-text {
line-height: 18px;
}
#List .e-list-header .e-text {
font-family: sans-serif;
font-size: 18px;
line-height: 26px;
}
#List .category {
font-family: "serif";
font-weight: 600;
font-size: 19px;
}
#List .name {
font-size: 15px;
font-weight: 500;
line-height: 23px;
}
#List .content {
line-height: 19px;
font-size: 13px;
font-weight: 200;
}
#List .e-hover {
transition: 0.5s;
}
.timeStamp {
font-size: small;
margin-bottom: 1px;
margin-top: -17px;
}
.bookmark::before {
color: grey;
float: right;
line-height: 0;
margin-bottom: 1px;
font-family: "Bookmarks";
content: "\e700";
margin-left: 3px;
margin-right: 3px;
font-size: 16px;
padding-top: 19px;
padding-bottom: 5px;
}
.share::before {
color: grey;
float: right;
line-height: 0;
margin-bottom: 1px;
font-family: "Bookmarks";
content: "\e701";
margin-left: 3px;
margin-right: 3px;
font-size: 13px;
padding-top: 19px;
padding-bottom: 5px;
}
.comments::before {
color: grey;
float: right;
line-height: 0;
margin-bottom: 1px;
font-family: "Bookmarks";
content: "\e703";
margin-left: 3px;
margin-right: 3px;
font-size: 15px;
padding-top: 19px;
padding-bottom: 5px;
}
.bookmark {
cursor: pointer;
}
.share {
cursor: pointer;
}
.comments {
cursor: pointer;
}
.description {
color: grey;
line-height: 20px;
font-size: 15px;
font-weight: 200;
text-align: justify;
}
/* csslint ignore:start */
@@font-face {
font-family: 'Bookmarks';
src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAAKAIAAAwAgT1MvMj0gSRgAAAEoAAAAVmNtYXDOI85qAAABkAAAAEJnbHlmRXCi8wAAAeAAAAFkaGVhZA8SahsAAADQAAAANmhoZWEHmQNtAAAArAAAACRobXR4D7gAAAAAAYAAAAAQbG9jYQDwAIAAAAHUAAAACm1heHABEQAyAAABCAAAACBuYW1lFuNPLwAAA0QAAAI9cG9zdLaVZAwAAAWEAAAAXQABAAADUv9qAFoEAAAA//4D6gABAAAAAAAAAAAAAAAAAAAABAABAAAAAQAAGHTc9V8PPPUACwPoAAAAANYFEqYAAAAA1gUSpgAAAAAD6gPqAAAACAACAAAAAAAAAAEAAAAEACYAAwAAAAAAAgAAAAoACgAAAP8AAAAAAAAAAQPuAZAABQAAAnoCvAAAAIwCegK8AAAB4AAxAQIAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUGZFZABA5wDnAwNS/2oAWgPqAJYAAAABAAAAAAAABAAAAAPoAAAD6AAAA+gAAAAAAAIAAAADAAAAFAADAAEAAAAUAAQALgAAAAYABAABAALnAecD//8AAOcA5wP//wAAAAAAAQAGAAgAAAABAAIAAwAAAAAAAAA+AIAAsgAAAAMAAAAAAxwD6gANABkAJQAAExE3FxEHLgEnNDcjDgElMxUzFSMVIzUjNTMHHgEXPgE3LgEnDgHQ190MWXcCCWU0RAGWKFBQKFBQlQJdRkZdAQFdRkZdAwn8+fn5AnMBAndZHx0BRWhQKFBQKA5GXQICXUZGXQEBXQAAAAABAAAAAAPqA+oAJAAACQEuASMOAQceARcyNjcBHgEXPgE3LgIHCQEWMz4BNy4BJw4BArn+QxM1HD5WAgJTQRwyEwHGC1I5P1UBAVOCKf5YAbUmND5WAQFWPkFUA2T+7hESAko3OUwBEQ7+6zJAAgJLOTpLASUBBgEMHAFLOTpLAQFLAAACAAAAAAPqA4EADwAcAAABHgEXMjcXJz4BNS4BJw4BBTMVNzMnJjU+ATc1IQIOA4ZlFROGLzM8AoZmZYb98YWBygIRBLOG/QYBvGWHAgRmhyBpQGWGAwOG0sLCBzA2h7MDiAAAAAASAN4AAQAAAAAAAAABAAAAAQAAAAAAAQAJAAEAAQAAAAAAAgAHAAoAAQAAAAAAAwAJABEAAQAAAAAABAAJABoAAQAAAAAABQALACMAAQAAAAAABgAJAC4AAQAAAAAACgAsADcAAQAAAAAACwASAGMAAwABBAkAAAACAHUAAwABBAkAAQASAHcAAwABBAkAAgAOAIkAAwABBAkAAwASAJcAAwABBAkABAASAKkAAwABBAkABQAWALsAAwABBAkABgASANEAAwABBAkACgBYAOMAAwABBAkACwAkATsgQm9va21hcmtzUmVndWxhckJvb2ttYXJrc0Jvb2ttYXJrc1ZlcnNpb24gMS4wQm9va21hcmtzRm9udCBnZW5lcmF0ZWQgdXNpbmcgU3luY2Z1c2lvbiBNZXRybyBTdHVkaW93d3cuc3luY2Z1c2lvbi5jb20AIABCAG8AbwBrAG0AYQByAGsAcwBSAGUAZwB1AGwAYQByAEIAbwBvAGsAbQBhAHIAawBzAEIAbwBvAGsAbQBhAHIAawBzAFYAZQByAHMAaQBvAG4AIAAxAC4AMABCAG8AbwBrAG0AYQByAGsAcwBGAG8AbgB0ACAAZwBlAG4AZQByAGEAdABlAGQAIAB1AHMAaQBuAGcAIABTAHkAbgBjAGYAdQBzAGkAbwBuACAATQBlAHQAcgBvACAAUwB0AHUAZABpAG8AdwB3AHcALgBzAHkAbgBjAGYAdQBzAGkAbwBuAC4AYwBvAG0AAAAAAgAAAAAAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAQIBAwEEAQUADGJvb2ttYXJrLWFkZApzaGFyZS0tLTAxF21lc3NhZ2VzLWluZm9ybWF0aW9uLTAxAAAAAAA=) format('truetype');
font-weight: normal;
font-style: normal;
}
/* csslint ignore:end */
#postImg {
margin-right: 25px;
margin-top: 30px;
}
#postContainer {
width: inherit;
margin-top: 10px;
display: inline-flex;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
Name = "IBM Open-Sources Web Sphere Liberty Code",
content = "In September, IBM announced that it would be open-sourcing the code for WebSphere...",
id = "1",
image = "https://ej2.syncfusion.com/demos/src/listview/images/1.png",
timeStamp = "Syncfusion Blog - October 19, 2017"
});
listdata.Add(new
{
Name = "Must Reads: 5 Big Data E-books to upend your development",
content = "Our first e-book was published in May 2012-jQuery Succinctly was the start of over...",
id = "2",
image = "https://ej2.syncfusion.com/demos/src/listview/images/2.png",
timeStamp = "Syncfusion Blog - October 18, 2017"
});
listdata.Add(new
{
Name = "The Syncfusion Global License: Your Questions, Answered ",
content = "Syncfusion recently hosted a webinar to cover the ins and outs of the Syncfusion global...",
id = "4",
image = "https://ej2.syncfusion.com/demos/src/listview/images/3.png",
timeStamp = "Syncfusion Blog - October 18, 2017"
});
listdata.Add(new
{
Name = "Know: What is Coming from Microsoft this Fall ",
content = "On October 17, Microsoft will release its Fall Creators Update for the Windows 10 platform...",
id = "5",
image = "https://ej2.syncfusion.com/demos/src/listview/images/6.png",
timeStamp = "Syncfusion Blog - October 17, 2017"
});
ViewBag.dataSource = listdata;
return View();
}
}
}
The dual list contains two ListView. This allows you to move list items from one list to another using the client-side events. This section explains how to integrate the ListView component to achieve dual list.
Here, two ListView components have been used to display the list items. An ej2-button is used to transfer data between the ListView, and a textbox is used to achieve the UI of filtering support.
The dual list supports:
In the ListView component, sorting is enabled using the sortOrder property, and the select event is triggered while selecting an item. Here, the select event is triggered to enable and disable button states.
concat
with the second ListView. This button is enabled only when the data source
of the first ListView is not empty.dataManager
has been
used to fetch data from the data source and display in ListView.@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
<div class="list_container">
<div id="list_container_1">
<input class="e-input" type="text" id="firstInput" placeholder="Filter" title="Type in a name">
@Html.EJS().ListView("list-1").DataSource((IEnumerable<object>)ViewBag.firstListData).Select("onFirstListSelect").SortOrder(Syncfusion.EJ2.Lists.SortOrder.Ascending).Render()
</div>
<div id="btn">
@Html.EJS().Button("firstBtn").Content(">>").Render()
@Html.EJS().Button("secondBtn").Content(">").Disabled(true).Render()
@Html.EJS().Button("thirdBtn").Content("<").Disabled(true).Render()
@Html.EJS().Button("fourthBtn").Content("<<").Render()
</div>
<div id="list_container_2">
<input class="e-input" type="text" id="secondInput" placeholder="Filter" title="Type in a name">
@Html.EJS().ListView("list-2").DataSource((IEnumerable<object>)ViewBag.secondListData).Select("onSeconListSelect").SortOrder(Syncfusion.EJ2.Lists.SortOrder.Ascending).Render()
</div>
</div>
<style>
.list_container {
height: 398px;
max-width: 485px;
margin: auto;
}
#list_container_1,
#list_container_2 {
width: 200px;
}
#list-1,
#list-2 {
height: 362px;
border: 1px solid #dddddd;
border-radius: 3px;
}
#list_container_1,
#list_container_2 {
display: inline-block;
}
.e-btn {
margin-bottom: 15px;
width: 40px;
height: 40px;
}
#btn {
display: inline-block;
width: 41px;
margin: 0 15px;
position: relative;
top: -53%;
transform: translateY(50%);
}
</style>
<script type="text/javascript">
var firstListObj, secondListObj, firstBtnObj, secondBtnObj, thirdBtnObj, fourthBtnObj, firstListData, secondListData;
window.onload = function () {
firstListObj = document.getElementById("list-1").ej2_instances[0];
secondListObj = document.getElementById("list-2").ej2_instances[0];
secondBtnObj = document.getElementById("secondBtn").ej2_instances[0];
thirdBtnObj = document.getElementById("thirdBtn").ej2_instances[0];
firstBtnObj = document.getElementById("firstBtn").ej2_instances[0];
fourthBtnObj = document.getElementById("fourthBtn").ej2_instances[0];
firstListData = firstListObj.dataSource.slice();
secondListData = secondListObj.dataSource.slice();
}
//Here we are moving all list items to second list on clicking move all button
document.getElementById("firstBtn").addEventListener('click', function () {
secondListObj.dataSource = Array.prototype.concat.call(firstListObj.dataSource, secondListObj.dataSource);
secondListObj.dataBind();
updateFirstListData();
firstListObj.removeMultipleItems(firstListObj.liCollection);
firstListData = firstListData.concat(firstListObj.dataSource);
secondListData = secondListObj.dataSource.slice();
firstBtnObj.disabled = true;
onFirstKeyUp();
setButtonState();
});
//Here we are moving selected list item to second list on clicking move button
document.getElementById("secondBtn").addEventListener('click', function () {
var e = firstListObj.getSelectedItems();
secondListObj.dataSource = Array.prototype.concat.call(secondListObj.dataSource, e.data);
secondListObj.dataBind();
updateFirstListData();
firstListObj.removeItem(e.item);
firstListData = firstListData.concat(firstListObj.dataSource);
secondListData = secondListObj.dataSource.slice();
onFirstKeyUp();
secondBtnObj.disabled = true;
setButtonState();
});
//Here we are moving selected list item to first list on clicking move button
document.getElementById("thirdBtn").addEventListener('click', function () {
var e = secondListObj.getSelectedItems();
firstListObj.dataSource = Array.prototype.concat.call(firstListObj.dataSource, e.data);
firstListObj.dataBind();
updateSecondListData();
secondListObj.removeItem(e.item);
secondListData = secondListData.concat(secondListObj.dataSource);
firstListData = firstListObj.dataSource.slice();
onSecondKeyUp();
thirdBtnObj.disabled = true;
setButtonState();
});
//Here we are moving all list items to first list on clicking move all button
document.getElementById("fourthBtn").addEventListener('click', function () {
firstListObj.dataSource = Array.prototype.concat.call(firstListObj.dataSource, secondListObj.dataSource);
firstListObj.dataBind();
updateSecondListData();
secondListObj.removeMultipleItems(secondListObj.liCollection);
secondListData = secondListData.concat(secondListObj.dataSource);
firstListData = firstListObj.dataSource.slice();
onSecondKeyUp();
setButtonState();
});
//Here we are updating ListView dataSource for First List
function updateFirstListData() {
Array.prototype.forEach.call(firstListObj.liCollection, function (list) {
firstListData.forEach(function (data, index) {
if (list.innerText.trim() === data.text) {
delete firstListData[index];
}
});
});
document.getElementById("firstInput").value = '';
var ds = [];
firstListData.forEach(function (data) {
ds.push(data);
})
firstListData = ds;
}
//Here we are updating ListView dataSource for second List
function updateSecondListData() {
Array.prototype.forEach.call(secondListObj.liCollection, function (list) {
secondListData.forEach(function (data, index) {
if (list.innerText.trim() === data.text) {
delete secondListData[index];
}
});
});
document.getElementById("secondInput").value = '';
var ds = [];
secondListData.forEach(function (data) {
ds.push(data);
})
secondListData = ds;
}
function onFirstListSelect() {
secondBtnObj.disabled = false;
}
function onSeconListSelect() {
thirdBtnObj.disabled = false;
}
//Here we are handling filtering of list items using dataManager for first List
function onFirstKeyUp(e) {
var value = document.getElementById("firstInput").value;
var data = new ej.data.DataManager(firstListData).executeLocal(new ej.data.Query().where('text', 'startswith', value, true));
if (!value) {
firstListObj.dataSource = firstListData.slice();
} else {
firstListObj.dataSource = data;
}
firstListObj.dataBind();
}
//Here we are handling filtering of list items using dataManager for second List
function onSecondKeyUp(e) {
var value = document.getElementById("secondInput").value;
var data = new ej.data.DataManager(secondListData).executeLocal(new ej.data.Query().where('text', 'startswith', value, true));
if (!value) {
secondListObj.dataSource = secondListData.slice();
} else {
secondListObj.dataSource = data;
}
secondListObj.dataBind();
}
//Here we are changing the button state
function setButtonState() {
if (firstListObj.dataSource.length) {
firstBtnObj.disabled = false;
} else {
firstBtnObj.disabled = true;
secondBtnObj.disabled = true;
}
if (secondListObj.dataSource.length) {
fourthBtnObj.disabled = false;
} else {
fourthBtnObj.disabled = true;
thirdBtnObj.disabled = true;
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
text = "Hennessey Venom",
id = "list-01"
}); listdata.Add(new
{
text = "Bugatti Chiron",
id = "list-02"
}); listdata.Add(new
{
text = "Bugatti Veyron Super Sport",
id = "list-03"
}); listdata.Add(new
{
text = "SSC Ultimate Aero",
id = "list-04"
}); listdata.Add(new
{
text = "Koenigsegg CCR",
id = "list-05"
}); listdata.Add(new
{
text = "McLaren F1",
id = "list-06"
});
List<object> listdata1 = new List<object>();
listdata1.Add(new
{
text = "Aston Martin One- 77",
id = "list-07"
});
listdata1.Add(new
{
text = "Jaguar XJ220",
id = "list-08"
});
listdata1.Add(new
{
text = "McLaren P1",
id = "list-09"
});
listdata1.Add(new
{
text = "Ferrari LaFerrari",
id = "list-10"
});
ViewBag.firstListData = listdata;
ViewBag.secondListData = listdata1;
return View();
}
}
}
To load list items in child list dynamically, push the new list item data into the existing
dataSource
using
the select
event.
Refer to the following steps to load list item into the child list:
select
event that
triggers selecting list item in the ListView component. By using the select event, you can push the new list item to the child
list of the data source on specifying its item index. Item index can be obtained from the
SelectEventArgs
of the
select event.@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists
@Html.EJS().ListView("listview").DataSource((IEnumerable<object>)ViewBag.dataSource).Fields(new ListViewFieldSettings { IconCss = "icon", Tooltip = "text" }).Select("onSelect").ShowIcon(true).ShowHeader(true).HeaderTitle("Folders").Render()
<style>
#listview {
display: block;
max-width: 350px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
#listview.e-listview .e-list-icon {
height: 24px;
width: 30px;
}
.folder, .file {
background: url('https://ej2.syncfusion.com/demos/src/listview/images/file_icons.png') no-repeat;
background-size: 302%;
}
.folder {
background-position: -5px -466px;
}
.file {
background-position: -5px -151px;
}
/* csslint ignore:start */
.new-list {
color: deeppink !important;
}
/* csslint ignore:end */
</style>
<script>
//Select event to add new list item in child page
function onSelect(args) {
//Add new file to the child page of selected list item
this.dataSource[args.index].child.push({ id: '01-02', text: 'Newly Added File', icon: 'file', htmlAttributes: { role: 'li', class: 'new-list' } });
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
id = "01",
text = "Music",
icon = "folder",
child = new List<object>() { new { id = "01-01", text = "Gouttes.mp3", icon = "file" } }
});
listdata.Add(new
{
id = "02",
text = "Videos",
icon = "folder",
child = new List<object>() {
new { id= "02-01", text= "Naturals.mp4", icon= "file" },
new { id= "02-02", text= "Wild.mpeg", icon= "file" },
}
});
listdata.Add(new
{
id = "03",
text = "Documents",
icon = "folder",
child = new List<object>() {
new { id= "03-01", text= "Environment Pollution.docx", icon= "file" },
new { id= "03-02", text= "Global Water, Sanitation, & Hygiene.docx", icon= "file" },
new { id= "03-03", text= "Global Warming.ppt", icon= "file" },
new { id= "03-04", text= "Social Network.pdf", icon= "file" },
new { id= "03-05", text= "Youth Empowerment.pdf", icon= "file" }
}
});
listdata.Add(new
{
id = "04",
text = "Pictures",
icon = "folder",
child = new List<object>() {
new {
id= "04-01", text= "Camera Roll", icon= "folder",
child= new List<object>() {
new { id= "04-01-01", text= "WIN_20160726_094117.JPG", icon= "file" },
new { id= "04-01-02", text= "WIN_20160726_094118.JPG", icon= "file" },
new { id= "04-01-03", text= "WIN_20160726_094119.JPG", icon= "file" }
}
},
new {
id= "04-02", text= "Wind.jpg", icon= "file"
},
new {
id= "04-02", text= "Stone.jpg", icon= "file"
},
new {
id= "04-02", text= "Home.jpg", icon= "file"
},
new {
id= "04-02", text= "Bridge.png", icon= "file"
}
}
});
listdata.Add(new
{
id = "05",
text = "Downloads",
icon = "folder",
child = new List<object>() {
new { id= "05-01", text= "UI-Guide.pdf", icon= "file" },
new { id= "05-02", text= "Tutorials.zip", icon= "file" },
new { id= "05-03", text= "Game.exe", icon= "file" },
new { id= "05-04", text= "TypeScript.7z", icon= "file" },
}
});
ViewBag.dataSource = listdata;
return View();
}
}
}
The ListView component supports wrapping list items into a group based on the category. The category of each list item can be mapped with groupBy field of the data source. You can display grouped list items count in the list-header using the group header template. Refer to the following code sample to display grouped list item count.
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
@{
var template = "<div class='settings'>"
+ "<div id='postContainer'><div id='postImg'>"
+ "<img src=${image} style='height:35px;width:35px;border-radius:50%; border: 1px solid #ccc;' /></div>"
+ "<div id='content'><div class='name'>${Name}</div><div id='info'>${contact}</div></div></div>";
}
@Html.EJS().ListView("List").DataSource((IEnumerable<object>)ViewBag.dataSource).Fields(new ListViewFieldSettings { GroupBy = "category", Text = "Name" }).GroupTemplate("<div><span class='category'>${items[0].category}</span> <span class='count'> ${items.length} Item(s)</span></div>").Template(template).Render()
<style>
.count{
float:right;
}
#List {
display: block;
margin: auto;
border: 1px solid;
border-color: #ccc;
border-color: rgba(0, 0, 0, 0.12);
width: 350px;
}
#List .settings {
height: auto;
}
#List .e-list-group-item {
height: 56px;
line-height: 56px;
}
#List .e-list-item {
height: 70px;
padding: 0;
cursor: pointer;
box-sizing: border-box;
}
#List .e-list-header .e-text {
font-family: sans-serif;
font-size: 18px;
line-height: 26px;
}
#List #content {
margin: 9px 0 0 15px;
}
#List .name {
font-size: 14px;
line-height: 25px;
font-weight: 500;
}
#info {
line-height: 20px;
font-size: 12px;
}
#postImg {
margin: 15px 9px 9px 9px;
}
#postContainer {
width: inherit;
margin: auto;
display: inline-flex;
}
</style>
<style>
#text {
margin-left: 10px;
margin-top: 20px;
}
#element {
max-width: 350px;
margin: auto;
margin-top: 10px;
display: block;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new { Name = "Nancy", contact = "(206) 555-985774", id = "1", image = "https://ej2.syncfusion.com/demos/src/grid/images/1.png", category = "Experience" });
listdata.Add(new { Name = "Janet", contact = "(206) 555-3412", id = "2", image = "https://ej2.syncfusion.com/demos/src/grid/images/3.png", category = "Fresher" });
listdata.Add(new { Name = "Margaret", contact = "(206) 555-8122", id = "4", image = "https://ej2.syncfusion.com/demos/src/grid/images/4.png", category = "Experience" });
listdata.Add(new { Name = "Andrew ", contact = "(206) 555-9482", id = "5", image = "https://ej2.syncfusion.com/demos/src/grid/images/2.png", category = "Experience" });
listdata.Add(new { Name = "Steven", contact = "(71) 555-4848", id = "6", image = "https://ej2.syncfusion.com/demos/src/grid/images/5.png", category = "Fresher" });
listdata.Add(new { Name = "Michael", contact = "(71) 555-7773", id = "7", image = "https://ej2.syncfusion.com/demos/src/grid/images/6.png", category = "Experience" });
listdata.Add(new { Name = "Robert", contact = "(71) 555-5598", id = "8", image = "https://ej2.syncfusion.com/demos/src/grid/images/7.png", category = "Fresher" });
listdata.Add(new { Name = "Laura", contact = "(206) 555-1189", id = "9", image = "https://ej2.syncfusion.com/demos/src/grid/images/8.png", category = "Experience" });
ViewBag.dataSource = listdata;
return View();
}
}
}
The filtered data can be displayed in the ListView component depending upon on user inputs using the
DataManager
. Refer to the
following steps to render the ListView with filtered data.
dataSource
, and set
the sortOrder
property.keyup
event for textbox to perform filtering operation. To filter list data, pass the list data source to the
DataManager
, manipulate the data using the
executeLocal
method,
and then update filtered data as ListView dataSource.@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
<div id="sample">
<input class="e-input" type="text" id="textbox" placeholder="Filter" title="Type in a name">
@Html.EJS().ListView("list").DataSource((IEnumerable<object>)ViewBag.dataSource).Fields(new ListViewFieldSettings { Id = "id", Text = "text" }).SortOrder(SortOrder.Ascending).Render()
</div>
<style>
#list {
box-shadow: 0 1px 4px #ddd;
border-bottom: 1px solid #ddd;
}
#sample {
height: 220px;
margin: 0 auto;
display: block;
max-width: 350px;
}
</style>
<script>
document.getElementById("textbox").addEventListener("keyup", onKeyUp);
//Here, the list items are filtered using the DataManager instance for ListView
function onKeyUp() {
var listData = @(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.dataSource)));
var listObj = (document.getElementById("list")).ej2_instances[0];
var value = (document.getElementById("textbox")).value;
var data = new ej.data.DataManager(listData).executeLocal(
new ej.data.Query().where("text", "startswith", value, true)
);
if (!value) {
listObj.dataSource = listData.slice();
} else {
listObj.dataSource = data;
}
listObj.dataBind();
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
text = "Hennessey Venom",
id = "list-01"
}); listdata.Add(new
{
text = "Bugatti Chiron",
id = "list-02"
}); listdata.Add(new
{
text = "Bugatti Veyron Super Sport",
id = "list-03"
}); listdata.Add(new
{
text = "SSC Ultimate Aero",
id = "list-04"
}); listdata.Add(new
{
text = "Koenigsegg CCR",
id = "list-05"
}); listdata.Add(new
{
text = "McLaren F1",
id = "list-06"
});
ViewBag.dataSource = listdata;
return View();
}
}
}
In this demo, data has been filtered with starting character of the list items. You can also filter list items with ending character by passing the
endswith
in where clause instead ofstartswith
.
You can add or remove list items from the ListView component using the
addItem
and
removeItem
methods.
Refer to the following steps to add or remove a list item.
addItem
method to add a
new list item on clicking the Add Item button.removeItem
method.@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
<div id="sample">
@Html.EJS().ListView("sample-list-flat").DataSource((IEnumerable<object>)ViewBag.dataSource).Fields(new ListViewFieldSettings { IconCss = "icon", Text = "text" }).ActionComplete("onComplete").Template("<div class='text-content'> ${text} <span class = 'delete-icon'></span> </div>").Render()
@Html.EJS().Button("btn").Content("Add Item").Render()
</div>
<style>
#sample-list-flat {
margin: 40px auto;
max-width: 350px;
}
#btn {
margin: 40px auto;
display: block;
}
/* csslint ignore:start */
@@font-face {
font-family: "e-icon";
src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAAKAIAAAwAgT1MvMj1tSfIAAAEoAAAAVmNtYXDnEOdVAAABiAAAADZnbHlmXOniGAAAAcgAAAFAaGVhZBC1AhkAAADQAAAANmhoZWEIUQQDAAAArAAAACRobXR4CAAAAAAAAYAAAAAIbG9jYQCgAAAAAAHAAAAABm1heHABDgCYAAABCAAAACBuYW1lv4Bt4QAAAwgAAAIZcG9zdJx8QW4AAAUkAAAAOwABAAAEAAAAAFwEAAAAAAAD9AABAAAAAAAAAAAAAAAAAAAAAgABAAAAAQAApWcDV18PPPUACwQAAAAAANbRXpQAAAAA1tFelAAAAAAD9AP0AAAACAACAAAAAAAAAAEAAAACAIwAAgAAAAAAAgAAAAoACgAAAP8AAAAAAAAAAQQAAZAABQAAAokCzAAAAI8CiQLMAAAB6wAyAQgAAAIABQMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUGZFZABA5wDnAAQAAAAAXAQAAAAAAAABAAAAAAAABAAAAAQAAAAAAAACAAAAAwAAABQAAwABAAAAFAAEACIAAAAEAAQAAQAA5wD//wAA5wD//wAAAAEABAAAAAEAAAAAAAAAoAAAAAIAAAAAA/QD9AALAIsAAAEHFwcnByc3JzcXNwUfHz8fLx8PHgLuhIRrg4NrhIRrg4P9iQECAwQGBwcJCwsMDQ4PDxEREhMUFBUWFhcXFxkYGRkaGhkZGBkXFxcWFhUUFBMSEREPDw4NDAsLCQcHBgQDAgEBAgMEBgcHCQsLDA0ODw8RERITFBQVFhYXFxcZGBkZGhoZGRgZFxcXFhYVFBQTEhERDw8ODQwLCwkHBwYEAwICg4OGa4SEa4ODaoCE7hoZGRgZFxcXFhYVFBQTEhERDw8ODQwLCwkHBwYEAwIBAQIDBAYHBwkLCwwNDg8PERESExQUFRYWFxcXGRgZGRoaGRkYGRcXFxYWFRQUExIREQ8PDg0MCwsJBwcGBAMCAQECAwQGBwcJCwsMDQ4PDxEREhMUFBUWFhcXFxkYGRkAAAASAN4AAQAAAAAAAAABAAAAAQAAAAAAAQAGAAEAAQAAAAAAAgAHAAcAAQAAAAAAAwAGAA4AAQAAAAAABAAGABQAAQAAAAAABQALABoAAQAAAAAABgAGACUAAQAAAAAACgAsACsAAQAAAAAACwASAFcAAwABBAkAAAACAGkAAwABBAkAAQAMAGsAAwABBAkAAgAOAHcAAwABBAkAAwAMAIUAAwABBAkABAAMAJEAAwABBAkABQAWAJ0AAwABBAkABgAMALMAAwABBAkACgBYAL8AAwABBAkACwAkARcgZGVsZXRlUmVndWxhcmRlbGV0ZWRlbGV0ZVZlcnNpb24gMS4wZGVsZXRlRm9udCBnZW5lcmF0ZWQgdXNpbmcgU3luY2Z1c2lvbiBNZXRybyBTdHVkaW93d3cuc3luY2Z1c2lvbi5jb20AIABkAGUAbABlAHQAZQBSAGUAZwB1AGwAYQByAGQAZQBsAGUAdABlAGQAZQBsAGUAdABlAFYAZQByAHMAaQBvAG4AIAAxAC4AMABkAGUAbABlAHQAZQBGAG8AbgB0ACAAZwBlAG4AZQByAGEAdABlAGQAIAB1AHMAaQBuAGcAIABTAHkAbgBjAGYAdQBzAGkAbwBuACAATQBlAHQAcgBvACAAUwB0AHUAZABpAG8AdwB3AHcALgBzAHkAbgBjAGYAdQBzAGkAbwBuAC4AYwBvAG0AAAAAAgAAAAAAAAAKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAQIBAwARY2lyY2xlLWNsb3NlLS0tMDIAAAA=) format("truetype");
font-weight: normal;
font-style: normal;
}
/* csslint ignore:end */
#sample-list-flat .delete-icon::after {
font-family: "e-icon";
content: "\e700";
float: right;
cursor: pointer;
}
</style>
<script>
//Event handler to add the list item on button click
document.getElementById("btn").onclick = () => {
var listviewInstance = document.getElementById("sample-list-flat").ej2_instances[0];
var data = {
text: "Koenigsegg - " + (Math.random() * 1000).toFixed(0),
id: (Math.random() * 1000).toFixed(0).toString(),
icon: "delete-icon"
};
listviewInstance.addItem([data]);
setTimeout(() => {
var newEle = document.querySelectorAll('[data-uid="' + data.id + '"]');
newEle[0].addEventListener("click", deleteItem.bind(this));
}, 100);
};
//Method for actionComplete handler
function onComplete() {
var iconEle = document.getElementsByClassName("delete-icon");
//Event handler to bind the click event for delete icon
Array.prototype.forEach.call(iconEle, (element) => {
element.addEventListener("click", deleteItem.bind(this));
});
}
//Method to delete the list item
function deleteItem(args) {
var listviewInstance = document.getElementById("sample-list-flat").ej2_instances[0];
args.stopPropagation();
var liItem = (args.target).parentElement.parentElement;
listviewInstance.removeItem(liItem);
onComplete();
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new { text= "Hennessey Venom", id= "1", icon= "delete-icon" });
listdata.Add(new { text= "Bugatti Chiron", id= "2", icon= "delete-icon" });
listdata.Add(new { text= "Bugatti Veyron Super Sport", id= "3", icon= "delete-icon" });
listdata.Add(new { text= "Aston Martin One- 77", id= "4", icon= "delete-icon" });
listdata.Add(new { text= "Jaguar XJ220", id= "list-5", icon= "delete-icon" });
listdata.Add(new { text= "McLaren P1", id= "6", icon= "delete-icon" });
ViewBag.dataSource = listdata;
return View();
}
}
}
The ListView component triggers events based on its actions. The events can be used as extension points to perform custom operations. Refer to the following steps to trace the ListView events:
actionBegin
,
actionComplete
,
and select
events.SelectEventArgs
in the
select event, and display the selected list item text in the event trace panel while selecting list items.@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
<h4 id="evt-text">
<b>Event Trace</b>
</h4>
<div id="list-container">
<!-- ListView element -->
@Html.EJS().ListView("listview-def").DataSource((IEnumerable<object>)ViewBag.dataSource).ActionComplete("onActionComplete").ActionBegin("onActionBegin").Select("onSelect").Width("250").Render()
<div id="list_event">
<div id="evt">
<div class="eventarea" style="height:273px;overflow: auto">
<!-- Event log element -->
<span class="EventLog" id="EventLog" style="word-break: normal"></span>
</div>
<div class="evtbtn">
<!-- clear button element -->
@Html.EJS().Button("clear").Content("Clear").Render()
</div>
</div>
</div>
</div>
<style>
#list-container {
max-width: 600px;
margin: auto;
}
#EventLog b {
color: #388e3c;
}
#listview-def {
display: inline-block;
border: 1px solid #dcdcdc;
}
.evtbtn {
margin-top: 40px;
margin-left: 70px;
}
#evt {
border: 1px solid #dcdcdc;
padding: 10px;
width: 250px;
}
#list_event {
padding-left: 40px;
display: inline-block;
vertical-align: top;
}
</style>
<script>
//Clears the event log details
document.getElementById("clear").onclick = () => {
document.getElementById("EventLog").innerHTML = "";
};
//Handler for actionBegin event trace
function onActionBegin() {
appendElement("<b>actionBegin </b> event is triggered<hr>");
}
//Handler for select event trace
function onSelect(args) {
appendElement(args.text + "<b> is selected</b><hr>");
}
//Handler for actionComplete event trace
function onActionComplete() {
appendElement("<b>actionComplete</b> is triggered <hr>");
}
//Display event log
function appendElement(html) {
var span = document.createElement("span");
span.innerHTML = html;
var log = document.getElementById("EventLog");
log.insertBefore(span, log.firstChild);
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new { text= "Hennessey Venom", id= "1", icon= "delete-icon" });
listdata.Add(new { text= "Bugatti Chiron", id= "2", icon= "delete-icon" });
listdata.Add(new { text= "Bugatti Veyron Super Sport", id= "3", icon= "delete-icon" });
listdata.Add(new { text= "Aston Martin One- 77", id= "4", icon= "delete-icon" });
listdata.Add(new { text= "Jaguar XJ220", id= "list-5", icon= "delete-icon" });
listdata.Add(new { text= "McLaren P1", id= "6", icon= "delete-icon" });
ViewBag.dataSource = listdata;
return View();
}
}
}
You can customize the ListView using the
template property. Refer
to the following steps to customize ListView as mobile contact view with our ej2-avatar
.
List<object> listdata = new List<object>();
listdata.Add(new
{
text = "Jenifer",
contact = "(206) 555-985774",
id = "1",
avatar = "",
pic = "pic01"
});
listdata.Add(new
{
text = "Amenda",
contact = "(206) 555-3412",
id = "2",
avatar = "A",
pic = ""
});
avatar
classes in ListView template to customize contact icon. In the following codes, medium size avatar has been
set using the class name e-avatar e-avatar-circle
from data source. var template: "<div class='settings'>" +
"${if(avatar!=='')}" +
"<span class='e-avatar e-avatar-circle'>${avatar}</span>" +
"${else}" +
"<span class='${pic} e-avatar e-avatar-circle'> </span>" +
"${/if}" +
"<div id='content'>" +
"<div class='name'>${text}</div>" +
"<div id='info'>${contact}</div>" +
"</div>";
Avatars can be set in different sizes in avatar classes. To know more about avatar classes, refer to Avatar.
sortOder
property of ListView.showHeader
property, and set the
headerTitle
as Contacts
.@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
@{
var template = "<div class='settings'>" +
"${if(avatar!=='')}" +
"<span class='e-avatar e-avatar-circle'>${avatar}</span>" +
"${else}" +
"<span class='${pic} e-avatar e-avatar-circle'> </span>" +
"${/if}" +
"<div id='content'>" +
"<div class='name'>${text}</div>" +
"<div id='info'>${contact}</div>" +
"</div>";
}
<!-- ListView element -->
@Html.EJS().ListView("List").DataSource((IEnumerable<object>)ViewBag.dataSource).Fields(new ListViewFieldSettings { Text = "Name" }).SortOrder(SortOrder.Ascending).Width("350").Template(template).ShowHeader(true).HeaderTitle("Contacts").Render()
<style>
#List {
margin: 0 auto;
border: 1px solid #ccc;
}
#List .e-list-item {
height: 60px;
cursor: pointer;
}
#List .e-list-header .e-text {
font-family: sans-serif;
font-size: 18px;
line-height: 16px;
}
#List #content {
margin: 0;
}
#List .e-list-header {
background: rgb(2, 120, 215);
color: white;
}
#List #info,
#List .name {
font-size: 14px;
margin: 0 60px;
line-height: 20px;
}
#List .name {
padding-top: 8px;
font-weight: 500;
}
.pic01 {
background-image: url("https://ej2.syncfusion.com/demos/src/grid/images/1.png");
}
.pic02 {
background-image: url("https://ej2.syncfusion.com/demos/src/grid/images/3.png");
}
.pic03 {
background-image: url("https://ej2.syncfusion.com/demos/src/grid/images/5.png");
}
.pic04 {
background-image: url("https://ej2.syncfusion.com/demos/src/grid/images/2.png");
}
#List .e-avatar {
position: absolute;
margin-top: 8px;
font-size: 14px;
}
#List .e-list-item:nth-child(1) .e-avatar {
background-color: #039be5;
}
#List .e-list-item:nth-child(2) .e-avatar {
background-color: #e91e63;
}
#List .e-list-item:nth-child(6) .e-avatar {
background-color: #009688;
}
#List .e-list-item:nth-child(8) .e-avatar {
background-color: #0088;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
text= "Jenifer",
contact= "(206) 555-985774",
id= "1",
avatar= "",
pic= "pic01"
});
listdata.Add(new
{
text= "Amenda",
contact= "(206) 555-3412",
id= "2",
avatar= "A",
pic= ""
});
listdata.Add(new
{
text= "Isabella",
contact= "(206) 555-8122",
id= "4",
avatar= "",
pic= "pic02"
});
listdata.Add(new
{
text= "William ",
contact= "(206) 555-9482",
id= "5",
avatar= "W",
pic= ""
});
listdata.Add(new
{
text= "Jacob",
contact= "(71) 555-4848",
id= "6",
avatar= "",
pic= "pic04"
});
listdata.Add(new
{
text= "Matthew",
contact= "(71) 555-7773",
id= "7",
avatar= "M",
pic= ""
});
listdata.Add(new
{
text= "Oliver",
contact= "(71) 555-5598",
id= "8",
avatar= "",
pic= "pic03"
});
listdata.Add(new
{
text= "Charlotte",
contact= "(206) 555-1189",
id= "9",
avatar= "C",
pic= ""
});
ViewBag.dataSource = listdata;
return View();
}
}
}
The features of the ListView component such as remote data-binding take more time to fetch data from corresponding dataSource/remote URL. In this case, you can use EJ2 Spinner to enhance the appearance of the UI. This section explains how to load a spinner component to groom the appearance.
Refer to the following code sample to render the spinner component.
ej.popups.createSpinner({
target: document.getElementById('spinner')
});
ej.popups.showSpinner(document.getElementById('spinner'));
Refer to the following code sample to render the ListView component.
<!-- ListView element -->
@Html.EJS().ListView("element").DataSource(dataManger =>
{dataManger.Url("http://js.syncfusion.com/ejServices/Wcf/Northwind.svc/").CrossDomain(true);
}).Query("new ej.data.Query().from('Products').select('ProductID,ProductName').take(10)").ActionBegin("onBegin").Fields(new ListViewFieldSettings { Id = "ProductID", Text = "ProductName" }).ShowHeader(true).HeaderTitle("Product Name").Width("300").ActionComplete("oncomplete").Render()
Here, the data is fetched from Northwind
Service URL; it takes a few seconds to load the data. To enhance the UI, the
spinner component has been rendered initially. After the data is loaded from remote URL, the spinner component will be
hidden in ListView
actionComplete
event.
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
<!-- ListView element -->
@Html.EJS().ListView("element").DataSource(dataManger =>
{dataManger.Url("http://js.syncfusion.com/ejServices/Wcf/Northwind.svc/").CrossDomain(true);
}).Query("new ej.data.Query().from('Products').select('ProductID,ProductName').take(10)").ActionBegin("onBegin").Fields(new ListViewFieldSettings { Id = "ProductID", Text = "ProductName" }).ShowHeader(true).HeaderTitle("Product Name").Width("300").ActionComplete("oncomplete").Render()
<style>
#element {
display: block;
max-width: 350px;
min-height: 200px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
</style>
<script>
function oncomplete() {
document.getElementById('spinner').style.display = "none";
}
function onBegin() {
var ele = document.createElement('div');
ele.id = 'spinner';
document.getElementById('element').appendChild(ele);
ej.popups.createSpinner({
target: document.getElementById('spinner')
});
ej.popups.showSpinner(document.getElementById('spinner'));
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
return View();
}
}
}
The checkbox of the any list item can be hidden by using
htmlAttributes
of
fields
object. With
the help of htmlAttributes
we can add unique class to each list item that will be rendered from the data source, from
the CSS class we can hide the checkbox of the list item.
In this sample, we had hidden the multiple leaf node of nested list. The e-checkbox-hidden
class has been added in the data
source where the checkbox needs to be hidden. Refer the below snippet for simple data source.
{
text= 'New York',
id= '3002',
category= 'USA',
htmlAttributes= { 'class': 'e-file e-checkbox-hidden' }
}
Even though we have hidden the checkbox the functionality will be same for the list item which might affect the
getSelectedItems
method. So, to counteract that we will follow certain logic in the select
event. The Logic here is to
remove the e-active
class from the other checkbox hidden list item which will be added when we select on that item and
retain e-active
on currently selected item.
In this process we will exclude the visible checkbox list items and only consider the hidden checkbox items.
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
<!-- ListView element -->
@Html.EJS().ListView("folderCheckbox").DataSource((IEnumerable<object>)ViewBag.dataSource).Fields(new ListViewFieldSettings { Tooltip = "text" }).ShowHeader(true).HeaderTitle("Mixed Leaf Checkbox Hidden List").ShowCheckBox(true).Select("onSelect").Render()
<style>
#folderCheckbox {
border: 1px solid #dddddd;
border-radius: 3px;
width: 350px;
margin: auto;
}
#folderCheckbox .e-checkbox-hidden .e-checkbox-wrapper {
visibility: hidden;
}
</style>
<script>
function onSelect(args) {
var listviewInstance = document.getElementById("folderCheckbox").ej2_instances[0];
// Selecting all the e-active elements from the list.
var normalElements = Array.prototype.slice.call(listviewInstance.element.getElementsByClassName('e-checkbox-hidden'));
// Looping through all the selected element and removing e-active class
// to avoid behaviour interference with getSelectedItems method
normalElements.forEach((element) => {
element.classList.remove('e-active');
});
// Finally adding e-active class to currently selected item except checkbox item.
// because if it is checkbox item their actions will taken care from the source side itself.
if (args.item.classList.contains('e-checkbox-hidden')) {
args.item.classList.add('e-active');
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
text = "Asia",
id = "01",
category = "Continent",
child = new List<object>() { new { text = "India", id = "1", category = "Asia",
child= new List<object>() {
new { id= "1001", text= "Delhi", category= "India",htmlAttributes= new { @class= "e-file e-checkbox-hidden" } },
new {text= "Kashmir", id= "1002", category= "India",htmlAttributes= new { @class= "e-file e-checkbox-hidden" }},
new { text= "Goa",id= "1003", category= "India",htmlAttributes= new { @class= "e-file" } }
}
},
new { text = "China",id = "2",category = "Asia",
child = new List<object>() {
new { text = "Zhejiang", id = "2001", category = "China",htmlAttributes= new { @class= "e-file" } },
new {text= "Hunan",id= "2002", category= "China",htmlAttributes= new { @class= "e-file e-checkbox-hidden" }},
new { text= "Shandong", id= "2003",category= "China",htmlAttributes= new { @class= "e-file" }}
}
}
}
});
listdata.Add(new
{
text = "North America",
id = "02",
category = "Continent",
child = new List<object>() { new { text = "USA", id = "3", category = "North America",
child= new List<object>() {
new {text= "California", id= "3001", category= "USA",htmlAttributes= new { @class= "e-file e-checkbox-hidden" }},
new { text= "New York",id= "3002", category= "USA",htmlAttributes= new { @class= "e-file e-checkbox-hidden" } },
new { text= "Florida",id= "3003", category= "USA" ,htmlAttributes= new { @class= "e-file" }}
}
},
new { text = "Canada",id = "4",category = "North America",
child = new List<object>() {
new { text = "Ontario", id = "4001", category = "Canada",htmlAttributes= new { @class= "e-file e-checkbox-hidden" } },
new {text= "Alberta",id= "4002", category= "Canada",htmlAttributes= new { @class= "e-file" }},
new { text= "Manitoba", id= "4003",category= "Canada",htmlAttributes= new { @class= "e-file" }}
}
}
}
});
listdata.Add(new
{
text = "Europe",
id = "03",
category = "Continent",
child = new List<object>() { new { text = "Germany", id = "5", category = "Europe",
child= new List<object>() {
new {text= "Berlin", id= "5001", category= "Germany",htmlAttributes= new { @class= "e-file e-checkbox-hidden" }},
new { text= "Bavaria",id= "5002", category= "Germany",htmlAttributes= new { @class= "e-file" } },
new { text= "Hesse",id= "5003", category= "Germany" ,htmlAttributes= new { @class= "e-file e-checkbox-hidden" }}
}
},
new { text = "France",id = "6",category = "Europe",
child = new List<object>() {
new { text = "Paris", id = "6001", category = "France" ,htmlAttributes= new { @class= "e-file" }},
new {text= "Lyon",id= "6002", category= "France",htmlAttributes= new { @class= "e-file e-checkbox-hidden" }},
new { text= "Marseille", id= "6003",category= "France",htmlAttributes= new { @class= "e-file" }}
}
}
}
});
listdata.Add(new
{
text = "Australia",
id = "04",
category = "Continent",
child = new List<object>() { new { text = "Australia", id = "7", category = "Australia",
child= new List<object>() {
new {text= "Sydney", id= "7001", category= "Australia",htmlAttributes= new { @class= "e-file e-checkbox-hidden" }},
new { text= "Melbourne",id= "7002", category= "Australia" ,htmlAttributes= new { @class= "e-file" }},
new { text= "Brisbane",id= "7003", category= "Australia" ,htmlAttributes= new { @class= "e-file" }}
}
},
new { text = "New Zealand",id = "8",category = "Australia",
child = new List<object>() {
new { text = "Milford Sound", id = "8001", category = "New Zealand",htmlAttributes= new { @class= "e-file" } },
new {text= "Tongariro National Park",id= "8002", category= "New Zealand",htmlAttributes= new { @class= "e-file" }},
new { text= "Fiordland National Park", id= "8003",category= "New Zealand",htmlAttributes= new { @class= "e-file e-checkbox-hidden" }}
}
},
}
});
listdata.Add(new
{
text = "Africa",
id = "05",
category = "Continent",
child = new List<object>() { new { text = "Morocco", id = "9", category = "Africa",
child= new List<object>() {
new {text= "Rabat", id= "9001", category= "Morocco",htmlAttributes= new { @class= "e-file e-checkbox-hidden" }},
new { text= "Toubkal",id= "9002", category= "Morocco",htmlAttributes= new { @class= "e-file" } },
new { text= "Todgha Gorge",id= "9003", category= "Morocco" ,htmlAttributes= new { @class= "e-file e-checkbox-hidden" }}
}
},
new { text = "South Africa",id = "10",category = "Africa",
child = new List<object>() {
new { text = "Cape Town", id = "10001", category = "South Africa" ,htmlAttributes= new { @class= "e-file e-checkbox-hidden" }},
new {text= "Pretoria",id= "10002", category= "South Africa",htmlAttributes= new { @class= "e-file e-checkbox-hidden" }},
new { text= "Bloemfontein", id= "10003",category= "South Africa",htmlAttributes= new { @class= "e-file" }}
}
},
}
});
ViewBag.dataSource = listdata;
return View();
}
}
}
In Listview, list items can be rendered in grid layout with following data manipulations.
In this section, we will discuss about rendering of list items in grid layout.
#element .e-list-item {
height: 100px;
width: 100px;
float: left;
}
In the below sample, we have rendered List items in grid layout.
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
@{
var template = "<img id='listImage' src='./apple.png' alt='apple' />";
}
<!-- ListView element -->
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource).Template(template).Render()
<style>
#element {
display: block;
max-width: 303px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
#element .e-list-item {
height: 100px;
width: 100px;
float: left;
padding: 0;
}
#listImage {
width: 55px;
height: 55px;
margin-left: 20px;
margin-top: 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
string[] listdata = { "1","2", "3", "4", "5", "6", "7", "8", "9" };
ViewBag.dataSource = listdata;
return View();
}
}
}
In this section, we will discuss about ListView data manipulations.
We can add list item using addItem
API. This will accept array of data as argument.
listViewInstance.addItem([{text: 'Apricot', id: '32'}]);
In the below sample, you can add new fruit item by clicking add button which will open dialog box with fruit name and image URL text box. After entering the item details, click the add button. This will add your new fruit item.
We can remove list item using removeItem
API. This will accept fields with id
or list item element as argument.
listViewInstance.removeItem({id: '32'});
In the below sample, you can remove fruit by hovering the fruit item which will show delete button and click that delete button to delete that fruit from your list.
Listview can be sorted either in Ascending or Descending order. To enable sorting in your ListView, set sortOrder
as Ascending
or Descending
.
@Html.EJS().ListView("element").SortOrder(SortOrder.Ascending).Render()
We can also set sorting after component initialization.
listViewInstance.sortOrder = 'Ascending'
In the below sample, we have sorted fruits in Ascending
order. To sort it in descending, click on sort order icon and vice versa.
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
@using Syncfusion.EJ2.Popups;
@{
var template = "<div class='fruits'><div class='first'><img id='listImage' src='${ imgUrl}' alt='fruit' /><button class='delete e-control e-btn e-small e-round e-delete-btn e-primary e-icon-btn' data-ripple='true'><span class='e-btn-icon e-icons delete-icon'></span></button></div><div class='fruitName'>${text}</div></div>";
}
<div id="container">
<div class="headerContainer">
<div class="e-input-group">
<input id="search" class="e-input" type="text" placeholder="Search fruits" />
<span class="e-input-group-icon e-input-search"></span>
</div>
<button id="sort" class="e-control e-btn e-small e-round e-primary e-icon-btn" title="Sort fruits" data-ripple="true">
<span class="e-btn-icon e-icons e-sort-icon-ascending"></span>
</button>
<button id="add" class="e-control e-btn e-small e-round e-primary e-icon-btn" title="Add fruit" data-ripple="true">
<span class="e-btn-icon e-icons e-add-icon"></span>
</button>
@Html.EJS().Dialog("dialog").ShowCloseIcon(true).Buttons(ViewBag.DialogButtons).Content("<div id='listDialog'><div class='input_name'><label for='name'>Fruit Name: </label><input id='name' class='e-input' type='text' placeholder='Enter fruit name' /></div><div><label for='imgurl'>Fruit Image: </label><input id='imgurl' class='e-input' type='text' placeholder='Enter image url' /></div></div>").Header("Add fruit").Width("300px").Visible(false).Render()
<!-- ListView element -->
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource).ActionComplete("wireEvents").Template(template).SortOrder(SortOrder.Ascending).Render()
</div>
</div>
<style>
#listImage {
width: 55px;
height: 55px;
margin-left: 25px;
}
#container {
max-width: 440px;
margin: auto;
margin-top: 130px;
box-shadow: 0 3px 6px lightgray;
}
#dialog {
top:auto !important;
}
.headerContainer {
height: 48px;
line-height: 48px;
background: rgb(2, 120, 215);
color: white;
margin-bottom: 3px;
}
.headerContainer .e-input-group {
margin-left: 20px;
width: 200px;
background: white;
height: 31px;
}
.headerContainer #search {
height: 21px;
margin-left: 10px;
}
#listDialog .input_name {
margin-bottom: 20px;
}
.headerContainer #add,
.headerContainer #sort {
float: right;
margin-right: 15px;
margin-top: 7px;
background: white;
color: black;
}
.headerContainer .e-input-search::before {
font-family: 'e-icons';
content: '\e961';
margin-top: 3px;
}
.headerContainer .e-input-group .e-input-group-icon.e-input-search {
padding: 0 10px 0 10px;
}
#element .e-list-item {
height: 110px;
width: 110px;
float: left;
padding: 0;
position: relative;
user-select: none;
}
#element .e-delete-btn {
float: right;
visibility: hidden;
margin-top: -10px;
}
#element .e-delete-btn.e-btn.e-small.e-round {
width: 2em;
height: 2em;
}
#element .e-btn.e-small.e-round .e-btn-icon.delete-icon {
font-size: 9px;
}
#element .e-list-item:hover .e-delete-btn {
visibility: visible;
background: red;
border-radius: 50%;
}
#element .fruits {
height: inherit;
width: inherit;
padding: 10px 0 10px 0;
}
#element .fruitName {
text-align: center;
}
.headerContainer .e-add-icon::before {
content: '\e823';
}
#element .delete-icon::before {
content: '\e7fc';
color: white;
}
.headerContainer .e-sort-icon-ascending::before {
content: '\e840';
}
.headerContainer .e-sort-icon-descending::before {
content: '\e83f';
}
</style>
<script>
var fruitsdata = @(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.dataSource)));
var listViewInstance;
window.onload = function () {
listViewInstance = document.getElementById("element").ej2_instances[0];
}
function addItem() {
var dialogObj = document.getElementById("dialog").ej2_instances[0];
(document.getElementById("name")).value = "";
(document.getElementById("imgurl")).value = "";
dialogObj.show()
}
function wireEvents() {
Array.prototype.forEach.call(document.getElementsByClassName('e-delete-btn'), (ele) => {
ele.addEventListener('click', onDeleteBtnClick);
});
document.getElementById("add").addEventListener('click', addItem);
document.getElementById("sort").addEventListener('click', sortItems);
document.getElementById("search").addEventListener("keyup", onKeyUp);
}
//Here we are removing list item
function onDeleteBtnClick(e) {
e.stopPropagation();
var li = e.currentTarget.closest(".e-list-item");
var data = listViewInstance.findItem(li);
listViewInstance.removeItem(data);
new ej.data.DataManager(fruitsdata).remove('id', { id: (data)["id"] });
}
//Here we are adding list item
function dlgButtonClick() {
var dialogObj = document.getElementById("dialog").ej2_instances[0];
var name = (document.getElementById("name")).value;
var url = (document.getElementById("imgurl")).value;
var id = Math.random() * 10000;
listViewInstance.addItem([{ text: name, id: id, imgUrl: url }]);
fruitsdata.push({ text: name, id: id, imgUrl: url });
listViewInstance.element.querySelector('[data-uid="' + id + '"]').getElementsByClassName('e-delete-btn')[0].addEventListener('click', onDeleteBtnClick);
dialogObj.hide();
}
//Here we are sorting list item
function sortItems() {
var ele = document.getElementById("sort").firstElementChild;
var des = ele.classList.contains('e-sort-icon-descending') ? true : false;
if (des) {
ele.classList.remove('e-sort-icon-descending');
ele.classList.add('e-sort-icon-ascending');
listViewInstance.sortOrder = 'Ascending'
} else {
ele.classList.remove('e-sort-icon-ascending');
ele.classList.add('e-sort-icon-descending');
listViewInstance.sortOrder = 'Descending'
}
listViewInstance.dataBind();
wireEvents();
}
//Here, the list items are filtered using the DataManager instance.
function onKeyUp() {
var value = (document.getElementById("search")).value;
var data = new ej.data.DataManager(fruitsdata).executeLocal(
new ej.data.Query().where("text", "startswith", value, true)
);
if (!value) {
listViewInstance.dataSource = fruitsdata.slice();
} else {
listViewInstance.dataSource = data;
listViewInstance.dataBind();
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Popups;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<DialogDialogButton> button = new List<DialogDialogButton>();
List<object> listdata = new List<object>();
listdata.Add(new { text = "Date", id = "1", imgUrl = "./dates.jpg" });
listdata.Add(new { text = "Fig", id = "2", imgUrl = "./fig.jpg" });
listdata.Add(new { text = "Apple", id = "3", imgUrl = "./apple.png" });
listdata.Add(new { text = "Apricot", id = "4", imgUrl = "./apricot.jpg" });
listdata.Add(new { text = "Grape", id = "5", imgUrl = "./grape.jpg" });
listdata.Add(new { text = "Strawberry", id = "6", imgUrl = "./strawberry.jpg" });
listdata.Add(new { text = "Pineapple", id = "7", imgUrl = "./pineapple.jpg" });
listdata.Add(new { text = "Melon", id = "8", imgUrl = "./melon.jpg" });
listdata.Add(new { text = "Lemon", id = "9", imgUrl = "./lemon.jpg" });
listdata.Add(new { text = "Cherry", id = "10", imgUrl = "./cherry.jpg" });
ViewBag.dataSource = listdata;
button.Add(new DialogDialogButton() { Click = "dlgButtonClick", ButtonModel = new ButtonModel() { isPrimary = true, content = "Add" } });
ViewBag.DialogButtons = button;
return View();
}
public class ButtonModel
{
public string content { get; set; }
public bool isPrimary { get; set; }
}
}
}
Listview data can be filtered with the help of dataManager
. After filtering the data, update ListView dataSource
with filtered data.
var value = document.getElementById("filter").value; //input text box value
var filteredData = new ej.data.DataManager(listdata).executeLocal(
new ej.data.Query().where("text", "startswith", value, true)
);
listViewInstance.dataSource = filteredData;
In the below sample, we can filter fruit items with the help of search text box. This will filter fruit items based on your input. Here we used startswith
of input text to filter data in DataManager.
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
@{
var template = "<img id='listImage' src='./apple.png' alt='apple' />";
}
<!-- ListView element -->
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource).Template(template).Render()
<style>
#element {
display: block;
max-width: 303px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
#element .e-list-item {
height: 100px;
width: 100px;
float: left;
padding: 0;
}
#listImage {
width: 55px;
height: 55px;
margin-left: 20px;
margin-top: 20px;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
string[] listdata = { "1","2", "3", "4", "5", "6", "7", "8", "9" };
ViewBag.dataSource = listdata;
return View();
}
}
}
In ListView component, we don’t have drag and drop support. But we can achieve this requirement using TreeView
component with ListView appearance.
Drag and Drop in TreeView component was enabled by setting allowDragAndDrop
to true
.
@Html.EJS().TreeView("element").Fields(ViewBag.TreeViewFields).AllowDragAndDrop(true).Render()
The TreeView component is used to represent hierarchical data in a tree like structure. So, list items in TreeView can be dropped to child of target element. we can prevent this behaviour by cancelling the nodeDragStop
and nodeDragging
events.
@Html.EJS().TreeView("element").Fields(ViewBag.TreeViewFields).AllowDragAndDrop(true).NodeDragging("onDragStop").NodeDragStop("onDragStop").Render()
function onDragStop(args) {
//Block the Child Drop operation in TreeView
var draggingItem = document.getElementsByClassName("e-drop-in");
if (draggingItem.length == 1) {
draggingItem[0].classList.add('e-no-drop');
args.cancel = true;
}
}
In the below sample, we have rendered draggable list items.
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
using Syncfusion.EJ2.Navigations;
@Html.EJS().TreeView("element").Fields(ViewBag.TreeViewFields).AllowDragAndDrop(true).NodeDragging("onDragStop").NodeDragStop("onDragStop").Render()
<style>
#element.e-treeview .e-ul {
padding: 0;
}
#element.e-treeview .e-list-item {
padding: 0 16px;
}
#element.e-treeview .e-text-content {
padding: 0;
}
#element.e-treeview .e-fullrow {
height: 36px;
}
#element.e-treeview .e-list-text {
line-height: 34px;
}
#element.e-treeview .e-list-item:last-child {
margin-bottom: 9px;
}
#element.e-treeview .e-list-item:first-child {
margin-top: 9px;
}
</style>
<script>
function onDragStop(args) {
//Block the Child Drop operation in TreeView
var draggingItem = document.getElementsByClassName("e-drop-in");
if (draggingItem.length == 1) {
draggingItem[0].classList.add('e-no-drop');
args.cancel = true;
}
}
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Syncfusion.EJ2.Navigations;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new
{
text = "Hennessey Venom",
id = "list-01"
}); listdata.Add(new
{
text = "Bugatti Chiron",
id = "list-02"
}); listdata.Add(new
{
text = "Bugatti Veyron Super Sport",
id = "list-03"
}); listdata.Add(new
{
text = "SSC Ultimate Aero",
id = "list-04"
}); listdata.Add(new
{
text = "Koenigsegg CCR",
id = "list-05"
}); listdata.Add(new
{
text = "McLaren F1",
id = "list-06"
}); listdata.Add(new
{
text = "Aston Martin One- 77",
id = "list-07"
}); listdata.Add(new
{
text = "Jaguar XJ220",
id = "list-08"
}); listdata.Add(new
{
text = "McLaren P1",
id = "list-09"
}); listdata.Add(new
{
text = "Ferrari LaFerrari",
id = "list-10"
});
ViewBag.dataSource = listdata;
return View();
}
}
}
We can use anchor
tag along with href
attribute in our ListView template
property for navigation.
var anchor_template = "<a target='_blank' href='${url}'>${name}</a>";
In the below sample, we have rendered ListView
with search engines URL.
@{
var anchor_template = "<a target='_blank' href='${url}'>${name}</a>";
}
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
@Html.EJS().ListView("element").DataSource((IEnumerable<object>)ViewBag.dataSource).Template(anchor_template).HeaderTitle("Search engines").ShowHeader(true).Render()
<style>
#element {
display: block;
max-width: 350px;
margin: auto;
border: 1px solid #dddddd;
border-radius: 3px;
}
#element a {
text-decoration: none;
}
#element .e-list-header {
background: rgb(2, 120, 215);
color: white;
font-size: 19px;
font-weight: 500;
}
</style>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listdata = new List<object>();
listdata.Add(new { name = "Google", url = "https://www.google.com" });
listdata.Add(new { name = "Bing", url = "https://www.bing.com" });
listdata.Add(new { name = "Yahoo", url = "https://www.yahoo.com" });
listdata.Add(new { name = "Ask.com", url = "https://www.ask.com" });
listdata.Add(new { name = "AOL.com", url = "https://www.aol.com"});
ViewBag.dataSource = listdata;
return View();
}
}
}
ListView can be customized as chat window. To achieve that, use the ListView template property and Avatar component.
* The Listview template property is used to showcase the ListView as chat window.
* Avatar component is used to design the image of contact person.
Refer the below template code snippet for Template of chat window.
var template = "<div class='settings'>" +
"${if(chat!=='receiver')}" +
"<div id='content'>" +
"<div class='name'>${text}</div>" +
"<div id='info'>${contact}</div></div>" +
"${if(avatar!=='')}" +
"<div id='image'><span class='e-avatar img1 e-avatar-circle'>${avatar}</span></div>" +
"${else}" +
"<div id='image'><span class='${pic} img1 e-avatar e-avatar-circle'> </span></div>" +
"${/if}" +
"${else}" +
"${if(avatar!=='')}" +
"<div id='image2'><span class='e-avatar img2 e-avatar-circle'>${avatar}</span></div>" +
"${else}" +
"<div id='image2'><span class='${pic} img2 e-avatar e-avatar-circle'> </span></div>" +
"${/if}" +
"<div id='content1'>" +
"<div class='name1'>${text}</div>" +
"<div id='info1'>${contact}</div>" +
"</div>" +
"${/if}" +
"</div>";
In ListView template, we have rendered the list items based on receiver and sender information from dataSource of listview.
* Use textbox to get message from user.
* Add the textbox message to ListView dataSource using [addItem](https://ej2.syncfusion.com/documentation/listview/api-listView.html?lang=typescript#additem) method.
document.getElementById('btn').addEventListener('click', (e) => {
var value = document.getElementById('name').value;
document.getElementById('List').ej2_instances[0].addItem([{ text: "Amenda", contact: value, id: "2", avatar: "A", pic: "", chat: "receiver" }]);
});
@{
var template = "<div class='settings'>" +
"${if(chat!=='receiver')}" +
"<div id='content'>" +
"<div class='name'>${text}</div>" +
"<div id='info'>${contact}</div></div>" +
"${if(avatar!=='')}" +
"<div id='image'><span class='e-avatar img1 e-avatar-circle'>${avatar}</span></div>" +
"${else}" +
"<div id='image'><span class='${pic} img1 e-avatar e-avatar-circle'> </span></div>" +
"${/if}" +
"${else}" +
"${if(avatar!=='')}" +
"<div id='image2'><span class='e-avatar img2 e-avatar-circle'>${avatar}</span></div>" +
"${else}" +
"<div id='image2'><span class='${pic} img2 e-avatar e-avatar-circle'> </span></div>" +
"${/if}" +
"<div id='content1'>" +
"<div class='name1'>${text}</div>" +
"<div id='info1'>${contact}</div>" +
"</div>" +
"${/if}" +
"</div>";
}
@using Syncfusion.EJ2
@using Syncfusion.EJ2.Lists;
@Html.EJS().ListView("List").DataSource((IEnumerable<object>)ViewBag.dataSource).Fields(new ListViewFieldSettings { Text = "text" }).Template(template).HeaderTitle("Chat").Width("350px").ShowHeader(true).Render()
<div style="width: 350px;margin: 0 auto;">
<input id="name" style="width: 275px" class="e-input" type="text" placeholder="Type your message" />
@Html.EJS().Button("btn").Content("Send").Render()
</div>
<style>
#btn {
float: right;
}
#List {
margin: 0 auto;
border: 1px solid #ccc;
}
#List .e-list-item {
height: auto;
cursor: pointer;
}
#List .e-list-header .e-text {
font-family: sans-serif;
font-size: 18px;
line-height: 26px;
}
#List #info,
#List .name {
font-size: 11px;
line-height: 20px;
}
#List .name {
padding-top: 3px;
font-weight: 500;
padding-left: 150px;
}
#List #info {
float: right;
margin-right: 10px;
}
.pic01 {
background-image: url("https://ej2.syncfusion.com/demos/src/grid/images/1.png");
}
.pic02 {
background-image: url("https://ej2.syncfusion.com/demos/src/grid/images/3.png");
}
.pic03 {
background-image: url("https://ej2.syncfusion.com/demos/src/grid/images/5.png");
}
.pic04 {
background-image: url("https://ej2.syncfusion.com/demos/src/grid/images/2.png");
}
.img2.e-avatar {
margin-left: 10px;
margin-top: 2px !important;
font-size: 13px;
}
#List #content1 {
width: 200px;
background-color: aliceblue;
display: inline-block;
margin: 5px;
}
#List #info1,
#List .name1 {
font-size: 11px;
line-height: 20px;
margin-left: 10px;
}
#List .name1 {
padding-top: 3px;
font-weight: 500;
}
#List #content {
margin: 5px;
width: 200px;
margin-left: 90px;
background-color: aliceblue;
display: inline-block;
}
#image {
float: right;
display: inline-block;
}
#image2 {
float: left;
display: inline-block;
}
.img1.e-avatar {
margin-right: 10px;
margin: 5px;
font-size: 13px;
}
.e-listview .e-list-item {
padding: 0px !important;
}
.e-listview .e-list-header {
color: white !important;
}
.e-listview .e-list-header {
background: rgb(2, 120, 215) !important;
}
#List.e-listview .e-list-item.e-hover {
background-color: transparent;
}
</style>
<script>
document.getElementById('btn').addEventListener('click', (e) => {
let value = document.getElementById('name').value;
document.getElementById('List').ej2_instances[0].addItem([{ text: "Amenda", contact: value, id: "2", avatar: "A", pic: "", chat: "receiver" }]);
document.getElementById('name').value = "";
});
</script>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
public class ListViewController : Controller
{
public IActionResult list()
{
List<object> listData = new List<object>();
listData.Add(new
{
text = "Jenifer",
contact = "Hi",
id = "1",
avatar = "",
pic = "pic01",
chat = "sender"
});
listData.Add(new { text = "Amenda", contact = "Hello", id = "2", avatar = "A", pic = "", chat = "receiver" });
listData.Add(new
{
text = "Jenifer",
contact = "What Knid of application going to launch",
id = "4",
avatar = "",
pic = "pic02",
chat = "sender"
});
listData.Add(new
{
text = "Amenda ",
contact = "A knid of Emergency broadcast App",
id = "5",
avatar = "A",
pic = "",
chat = "receiver"
});
listData.Add(new
{
text = "Jacob",
contact = "Can you please elaborate",
id = "6",
avatar = "",
pic = "pic04",
chat = "sender"
});
ViewBag.dataSource = listData;
return View();
}
}
}