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>
Related
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
I am trying to create a chart (using CharJs.js) with multiple data sets and have it displayed in my MVC project.
The idea is to not have the datasets manually predefined and then access each one of it in my view. This has to be built dynamically based on how many objects I have in a list.
This is my Model:
[DataContract]
public class DataPoint : IDataPoint
{
public DataPoint(string label, double y)
{
this.Label = label;
this.Y = y;
}
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "label")]
public string Label { get; set; }
//Explicitly setting the name to be used while serializing to JSON.
[DataMember(Name = "y")]
public Nullable<double> Y { get; set; }
//public List<double> Y { get; set; }
}
My Controller:
public async Task<ActionResult> ShowDetails(int ProductId, string PartId, string SupplierName, string fromSearchString, int? fromPage)
{
List<string> DbSupplierList = await _itScopeRepository.GetSupplierByPartId(Convert.ToInt32(PartId));
var ItScopeProduct = _itScopeRepository.GetProductById(ProductId);
ItScopeProduct.Supplier = SupplierName;
ItScopeProduct.SupplierList = DbSupplierList;
ViewBag.FromSearchString = fromSearchString;
ViewBag.FromPage = fromPage;
var obj = await CreateLineChart(DbSupplierList, PartId);
ItScopeProduct.DataPoints = obj;
return View("DetailsView", ItScopeProduct);
}
In my case here, the DataPoints is of type List<List<DataPoint>> and the list is being unfold in my View:
And this is my view:
<!DOCTYPE HTML>
<html>
<head>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
window.onload = function () {
var dataSecond = {
type: "line",
name:'#Html.Raw(JsonConvert.SerializeObject(Model.Supplier))',
showInLegend: true,
dataPoints: #Html.Raw(JsonConvert.SerializeObject(Model.DataPoints[0]))
};
var dataSecond2 = {
type: "line",
name:"Dexxit",
showInLegend: true,
dataPoints: #Html.Raw(JsonConvert.SerializeObject(Model.DataPoints[1]))
};
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "Product price history"
},
axisY: {
includeZero: false
},
toolTip: {
shared: true
},
data: [dataSecond, dataSecond2]
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
As you can see, right now I am taking each Object from the list manually and I would like to have it integrated in a loop where it creates an array of objects which will then be passed to my chart dataset.
I have tried something like this:
var testing;
var listOfDataPoints = [];
for(var i = 0; i < #Model.DataPoints.Count; i++){
testing = {
type: "line",
name: '#Html.Raw(JsonConvert.SerializeObject(Model.Supplier))',
showInLegend: true,
dataPoints: #Html.Raw(JsonConvert.SerializeObject(Model.DataPoints[i]))
};
listOfDataPoints.push(testing);
}
But unfortunately I cannot pass a javascript int value to my C# model, therefore making this solution unusable.
Now my question is: Is it possible to loop through my List of objects and create n amount (base on how many items are in my list)of javascript objects and have them inserted into an array?
The js obj should have the following structure:
var myDataset = {
type: "line",
name: '#Html.Raw(JsonConvert.SerializeObject(Model.Supplier))',
showInLegend: true,
dataPoints: #Html.Raw(JsonConvert.SerializeObject(Model.DataPoints[i]))
}
Ps. I am not very experienced with javascript, reason for why I am reaching for some guidance since I haven't found anything similar to what I need.
EDIT
I have tried the other way around: Having a c# loop and execute a javascript function where i am creating my objects.
var yest = [];
var listOfPoints = [];
function addMarker(supplier, datapo)
{
yest = {
type: "line",
name: "Dexxit",
showInLegend: true,
dataPoints: datapo
};
listOfPoints.push(yest);
}
#for(int i = 0; i < Model.DataPoints.Count; i++)
{
#:addMarker('#Html.Raw(JsonConvert.SerializeObject(Model.Supplier))', #Html.Raw(JsonConvert.SerializeObject(Model.DataPoints[i])));
}
But when i am assigning listOfPoints to my dataset, it shows an empty chart. Any ideas why?
Manage to find a working solution based on my last edit:
Had some small changes on my Controller and that was to change one of my Model (the one passed to my View) functions from List<List<DataPoint>> DataPoints {get;set;} to `List>> DataPoint{get;set;}
My new Controller:
public async Task<ActionResult> ShowDetails(int ProductId, string PartId, string SupplierName, string fromSearchString, int? fromPage)
{
List<string> DbSupplierList = await _itScopeRepository.GetSupplierByPartId(Convert.ToInt32(PartId));
var ItScopeProduct = _itScopeRepository.GetProductById(ProductId);
ItScopeProduct.Supplier = SupplierName;
ItScopeProduct.SupplierList = DbSupplierList;
ViewBag.FromSearchString = fromSearchString;
ViewBag.FromPage = fromPage;
var obj = await CreateLineChart(DbSupplierList, PartId);
List<KeyValuePair<string, List<IDataPoint>>> ConvertToInterface = new List<KeyValuePair<string, List<IDataPoint>>>();
foreach (var item in obj)
{
ConvertToInterface.Add(new KeyValuePair<string, List<IDataPoint>>(item.Key, item.Value.ToList<IDataPoint>()));
}
ItScopeProduct.DataPoints = ConvertToInterface;
return View("DetailsView", ItScopeProduct);
}
Updated View:
<!DOCTYPE HTML>
<html>
<head>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
window.onload = function () {
var listOfDataPoints = [];
var MyObj;
function addMarker(supplier, datapo)
{
var yest = {
type: "line",
name: supplier,
showInLegend: true,
dataPoints: datapo
};
return yest;
}
#for(int i = 0; i < Model.DataPoints.Count; i++)
{
#:MyObj = addMarker('#Html.Raw(JsonConvert.SerializeObject(Model.DataPoints[i].Key))', #Html.Raw(JsonConvert.SerializeObject(Model.DataPoints[i].Value)));
#:listOfDataPoints.push(MyObj);
}
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title: {
text: "Product price history"
},
axisY: {
includeZero: false
},
toolTip: {
shared: true
},
data: listOfDataPoints
});
chart.render();
}
</script>
</head>
<body>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
</body>
</html>
My chart is now dynamically built and it can show data based on what is in my Model.DataPoints.
I hope this can be of some help for someone in the same position.
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)) {
I'm trying to get data into HTML select with this code:
HTML:
<div ng-controller="Manufacturer">
<select ng-model="myManufacturer" ng-options="Manufacturer.name for Manufacturer in Manufacturers" class="form-control"></select>
</div>
JS:
angular.module('MyApp')
.controller('Manufacturer', ['$scope', function ($scope) {
$scope.CarManufacturer = null;
$.post("/Data/GetAllManufacturers");
$scope.Manufacturers = $.post.Data;
alert($scope.CarManufacturer);
// $scope.Manufacturers = [
// { name: 'Audi' , id: 1 },
// { name: 'Volvo', id: 2 },
// { name: 'BMW', id: 3 },
// { name: 'Skoda', id: 4 },
// { name: 'Siat', id: 5 }
//];
$scope.myManufacturer = $scope.Manufacturers[1]; // red
}]);
CONTROLLER:
public List<string> GetAllManufacturers()
{
dbCarEntities us = new dbCarEntities();
List<string> asd = us.CarManufacturers.Select(x => x.Name).ToList();
return asd;
}
Explanation:
I have an HTML select. I want to fill it with a list from my SQL table with Model Entity framework. So I need to go to a function and get back the list.
I tried also with JSON. It doesn't work either.
got it!!
angular.module('MyApp') // extending from previously created angularJS module in the First part
.controller('Part5Controller', function ($scope, LocationService) {
// expained about controller in Part2 // Here LocationService (Service) Injected
$scope.CountryID = null;
$scope.StateID = null;
$scope.CountryList = null;
$scope.StateList = null;
$scope.StateTextToShow = "Select State";
$scope.Result = "";
// Populate Country
LocationService.GetCountry().then(function (d) {
$scope.CountryList = d.data;
}, function (error) {
alert('Error!');
});
// Function For Populate State // This function we will call after select change country
$scope.GetState = function () {
$scope.StateID = null; // Clear Selected State if any
$scope.StateList = null; // Clear previously loaded state list
$scope.StateTextToShow = "Please Wait..."; // this will show until load states from database
//Load State
LocationService.GetState($scope.CountryID).then(function (d) {
$scope.StateList = d.data;
$scope.StateTextToShow = "Select State";
}, function (error) {
alert('Error!');
});
}
// Function for show result
$scope.ShowResult = function () {
$scope.Result = "Selected Country ID : " + $scope.CountryID + " State ID : " + $scope.StateID;
}
})
.factory('LocationService', function ($http) { // explained about factory in Part2
var fac = {};
fac.GetCountry = function () {
return $http.get('/Data/GetCountries')
}
fac.GetState = function (countryID) {
return $http.get('/Data/GetStates?countryID='+countryID)
}
return fac;
});
in $http.get we can put how many arguments we want.
in the controller :
public JsonResult GetCountries()
{
List<Country> allCountry = new List<Country>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
allCountry = dc.Countries.OrderBy(a => a.CountryName).ToList();
}
return new JsonResult { Data = allCountry, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
// Fetch State by Country ID
public JsonResult GetStates(int countryID)
{
List<State> allState = new List<State>();
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
allState = dc.States.Where(a => a.CountryID.Equals(countryID)).OrderBy(a => a.StateName).ToList();
}
return new JsonResult { Data = allState, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
and finally HTML view:
<div ng-controller="Part5Controller">
Country : <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetState()">
<option value="">Select Country</option>
</select>
State : <select ng-model="StateID" ng-options="I.StateID as I.StateName for I in StateList">
<option value="">{{StateTextToShow}}</option>
</select>
<input type="button" value="Get Selected Values" ng-click="ShowResult()"/>
<div style="padding:10px; font-weight:bold; border:1px solid #f3f3f3">
{{Result}}
</div>
</div>
#section scripts{
<script src="~/Scripts/AngularController/Part5Controller.js"></script>
}
I have got truble to format Price field. This is my view. I send record from controller as JSON object and it is working very well.
I want to format output as decimal with 2 places after dot like 100.00.
<link href="~/Content/jtable.2.4.0/jtable.2.4.0/themes/metro/blue/jtable.css" rel="stylesheet" type="text/css">
<link href="~/Content/jquery-ui-themes-1.11.2/themes/start/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="~/Scripts/jquery-1.11.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.jtable.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var lokalizacijaSrpski = {
serverCommunicationError: 'Greska u komunikaciji sa serverom.',
loadingMessage: 'Ucitavanje...',
noDataAvailable: 'Podaci nisu dostupni',
addNewRecord: 'Dodaj novi slog',
editRecord: 'Izmjeni',
areYouSure: 'Da li ste sigurni?',
deleteConfirmation: 'Da li ste sigurni da zelite da obrisete slog?',
save: 'Sacuvaj',
saving: 'Snimanje',
cancel: 'Odustani',
deleteText: 'Obrisi',
deleting: 'Brisanje',
error: 'Greska',
close: 'Zatvori',
cannotLoadOptionsFor: '{0} nemoguce ucitati!',
pagingInfo: 'Ukupno {2}, prikaz {0} od {1}',
gotoPageLabel: 'Idi na stranicu',
pageSizeChangeLabel: 'Broj redova',
canNotDeletedRecords: '{1} nemogucnost brisanja {0} sloga!'
};
$('#tXMLIndex').jtable({
messages: lokalizacijaSrpski,
title: 'XML PARSER',
paging: true,
pageSize: 10,
sorting: true,
actions: {
listAction: '/XmlParser/ListXML'
},
fields: {
XMLId: {
title: 'Xml id',
key: true,
create: false,
edit: false
},
Naziv: {
title: 'Naziv'
},
Price: {
title: 'Price'
}
},
recordUpdated: function(event, data) {
$('#tXMLIndex').jtable('load');
}
});
$('#tXMLIndex').jtable('load');
$.fn.focusTextToEnd = function() {
this.focus();
var $thisVal = this.val();
this.val('').val($thisVal);
return this;
}
$('#tbXMLIndexPretraga').focusTextToEnd();
$("#tbXMLIndexPretraga").keyup(function() {
$("#tXMLIndex").jtable('load', {
searchString: $("#tbXMLIndexPretraga").val()
});
});
});
</script>
<div id="tXMLIndex"></div>
Any suggestions?
Client side:
I have done number formatting using number_format.js, and it works well.
If you're willing to add the js to your page, this is how you'd do it:
Price: { title: 'Price',
edit: true,
list: true,
display: function (data) {
return number_format(data.record.price, 2, '.', ',');
}
},
number_format is as such:
function number_format(number, decimals, dec_point, thousands_sep)
Server-side:
In order to help you there, you'll have to post some code. What does your JSON look like? What comes out of /XmlParser/ListXML?
Server side look like
public JsonResult ListXML(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null, string searchString = null)
{
XmlReader readXML = new XmlReader();
var data = readXML.RetrunListOfProducts();
var lista = (from obj in data select new { XMLId=obj.ProductId,Naziv=obj.ProductName,Cjena=obj.ProductCost });
if (searchString != null)
{
lista = lista.Where(b => b.Naziv.Contains(searchString));
}
if (jtSorting == null)
{
jtSorting = "XMLId DESC";
}
switch (jtSorting)
{
case "XMLId ASC":
lista = lista.OrderBy(a => a.XMLId);
break;
case "Naziv ASC":
lista = lista.OrderBy(a => a.Naziv);
break;
case "Naziv DESC":
lista = lista.OrderByDescending(a => a.Naziv);
break;
case "Cjena ASC":
//lista = from obj in lista
// orderby Convert.ToDecimal(obj.Cjena) ascending
// select new { XMLId=obj.XMLId,Naziv=obj.Naziv,Cjena=obj.Cjena };
lista = from obj in lista
orderby obj.Cjena ascending
select new { XMLId = obj.XMLId, Naziv = obj.Naziv, Cjena = obj.Cjena };
break;
case "Cjena DESC":
//lista = from obj in lista
// orderby Convert.ToDecimal(obj.Cjena) descending
// select new { XMLId = obj.XMLId, Naziv = obj.Naziv, Cjena = obj.Cjena };
lista = from obj in lista
orderby obj.Cjena descending
select new { XMLId = obj.XMLId, Naziv = obj.Naziv, Cjena = obj.Cjena };
break;
default:
lista = lista.OrderByDescending(a => a.XMLId);
break;
}
var pagingLista = lista.Skip(jtStartIndex).Take(jtPageSize);
return this.Json(
new
{
Result = "OK",
Records = pagingLista.ToList(),
TotalRecordCount = lista.Count()
}
, JsonRequestBehavior.AllowGet
);
}