How to refresh Datatable using AngularJS mvc c#? - c#

I am create one small demo for show users list.for that show list used datatabel with angularjs. my listing show very well first time.but i want to create custom filter on that tabel.i want to get pass week data and i have return query also in controller and data getting propare but i don't know how to next time bind datatable in angularjs.
here first time bind datatable code:
app.controller('userscontroller', ['$scope', '$http', 'DTOptionsBuilder', 'DTColumnBuilder',
function ($scope, $http, DTOptionsBuilder, DTColumnBuilder) {
$scope.dtColumns = [
//DTColumnBuilder.newColumn("id", "User ID"),
DTColumnBuilder.newColumn("firstname", "First Name"),
DTColumnBuilder.newColumn("lastname", "Last Name"),
DTColumnBuilder.newColumn("email", "Email"),
]
debugger;
$scope.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
url: "/api/User/GetUserList",
type: "GET",
data: { 'searchRequest': null, fromDate: null, toDate: null },
contentType: "application/json; charset=utf-8",
})
.withPaginationType('full_numbers')
.withDisplayLength(50);
}])
this is my controller method:
[HttpGet]
[Route("GetUserList")]
public IHttpActionResult GetUserList(string searchRequest)
{
var UserList = db.UserInfo.ToList();
if (searchRequest != null)
{
if (searchRequest == "Past Week")
UserList = UserList.Where(t => Convert.ToDateTime(t.registrationdate).ToString("MMM dd yyyy") == DateTime.Now.AddDays(-7).ToString("MMM dd yyyy")).ToList();
}
var Details = UserList.Select(h => new
{
h.id,
h.firstname,
h.lastname,
h.registrationdate,
h.email,
h.contactnumber
});
return Json(Details);
}
this is my code for select past year data:
$scope.GetValue = function (event) {
var Type = $scope.ddlSearch;
$.ajax({
type: "GET",
cache: false,
url: '/api/User/GetUserList',
data: { searchRequest: Type },
success: function (response) {
}
});
this is my table html :
<table id="entry-grid" datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-hover"> </table>
i have try this code but i don't know how to reload datatable in anuglarjs.any one know then please help me for this task.

I would suggest to reassign $scope.dtOptions:
$scope.GetValue = function (event) {
var Type = $scope.ddlSearch;
$scope.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
url: "/api/User/GetUserList",
type: "GET",
cache: false,
data: { 'searchRequest': Type },
contentType: "application/json; charset=utf-8",
})
.withPaginationType('full_numbers')
.withDisplayLength(50);
};
Update:
I have made a simple example (with a MVC Controller)
Controller:
[HttpGet]
[Route("GetList")]
public ActionResult GetList(string psSelect)
{
List<dynamic> loList = new List<dynamic>();
if (string.IsNullOrEmpty(psSelect))
{
loList.Add(new { id = "1", firstname = "Tyler", lastname = "Durden" });
}
else
{
loList.Add(new { id = "2", firstname = "Big", lastname = "Lebowski" });
}
return new MyJsonResult(loList);
}
View:
<div data-ng-controller="mainController">
<input type="button" value="Refresh" data-ng-click="refreshList()" />
<table id="entry-grid" datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-hover"> </table>
</div>
Javascript:
$scope.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
url: "/Home/GetList",
type: "GET",
cache: false,
data: { 'psSelect': '' },
contentType: "application/json; charset=utf-8",
})
.withPaginationType('full_numbers')
.withDisplayLength(50);
$scope.refreshList = function () {
$scope.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
url: "/Home/GetList",
type: "GET",
cache: false,
data: { 'psSelect': 'refresh' },
contentType: "application/json; charset=utf-8",
})
.withPaginationType('full_numbers')
.withDisplayLength(50);
};

Related

Return Dynamic Array From Controller Asp.Net MVC

I can generate a Pie Chart Just like the picture by using the code below
<script>
var pieChartData = [
{ label: "Data 1", data: 16, color: "#62cb31", },
{ label: "Data 2", data: 6, color: "#A4E585", },
{ label: "Data 3", data: 22, color: "#368410", },
{ label: "Data 4", data: 32, color: "#8DE563", }
];
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
</script>
Now what I want to do is to generate the var data = [] dynamically from Controller. How to do this? Also the data is from the Database.
By Combining Pranav Patel and Ghanshyam Singh answers
I was able able to reach the desired output
Model
public class GenderPieChart_Model
{
public string GenderDesc { get; set; }
public int GenderID { get; set; }
}
Controller
public JsonResult Gender()
{
Dashboard_Layer data = new Dashboard_Layer();
var lst = data.Gender();
return Json(lst, JsonRequestBehavior.AllowGet);
}
Business Layer
public IEnumerable<GenderPieChart_Model> Gender()
{
List<GenderPieChart_Model> data = new List<GenderPieChart_Model>();
using (SqlConnection con = new SqlConnection(Connection.MyConn()))
{
SqlCommand com = new SqlCommand("dbo.sp_Project_DashBoard 4", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
GenderPieChart_Model value = new GenderPieChart_Model();
value.GenderDesc = Convert.ToString(reader.GetValue(0));
value.GenderID = Convert.ToInt32(reader.GetValue(1));
data.Add(value);
}
}
return data;
}
View
<div class="flot-chart-content" id="_ByGender" style="height: 150px"></div>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "#Url.Action("Gender", "Dashboard")",
content: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = data;
var pieChartData = [];
$.each(data, function (i,v) {
pieChartData.push({ label: v.GenderDesc, data: v.GenderID, color: "#62cb31", });
})
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByGender"), pieChartData, pieChartOptions);
}
})
});
</script>
you can call when your controller on ready event and after getting data (returned Json from your controller) can process further. You can try like below
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "<YOUR URL>",
data: "<YOUR PARAMETER IF NEEDED>",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){ //data is your json returned from controller
var myData = JSON.parse(data);
//create your 'pieChartData' from object 'myData'
//pieChartData =
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
}
});
});
</script>
Its simple just return Json from your controller:
first create a model class for the properties
public class Chart
{
public string label{get;set;}
public string data{get;set;}
public string color{get;set;}
}
MVC action method:-
public JsonResult Chart()
{
List<Chart> chartList=new List();
// Code to fetch Data in List chartList
return Json(chartList,JsonRequestBehaviour.AllowGet);
}
Ajax Call:-
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "/Controller/Chart",
data: "<YOUR PARAMETER IF NEEDED>",
dataType: "json",
success: function(data){
$.each(data,function(i,index){
// Code to plot Chart here
});
}
});
});
</script>

Linq query to delete the Child nodes or selected Node on the kendo treeview

I have a Treeview displaying all the nodes.The Structure is like
.P
.P1
.P2
.P3
.B
.B1
.B2
.B21
.B22
.B221
.B222
.B3
.C
.C1
.C2
And so on.Currently if i try to delete B its getting deleted along with the children on front end. But if i see in the database only B got deleted and childs are present. Below is the query i am Using to delete only the Parent. Can anyone suggest me how to delete the kids by getting the list of all nodes and checking whether it has childs or not and then deleting.Help is needed asap.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String removeTree(int id)
{
try
{
using (var context = new Data.Entities())
{
var delNode = context.Tree.Where(c => c.ID == id).First();
if (delNode != null)
{
context.Tree.Remove(delNode);
context.SaveChanges();
}
else
{
result.ReturnResult = false;
result.ReturnMessage = "Cannot delete.";
}
}
}
catch (Exception exc)
{
result.ReturnResult = false;
result.ReturnMessage = exc.Message;
}
JavaScriptSerializer JSON = new JavaScriptSerializer();
return JSON.Serialize(result);
}
kendo treeview:
function treeView() {
var treeMenu = new kendo.data.HierarchicalDataSource({
template: kendo.template($("#treeview-template").html()),
schema: {
data: function (response) {
return JSON.parse(response.d);
},
schema: {
model: {
hasChildren: true,
id: "id",
children: "HasChildren",
hasChildren: "HasChildren",
fields: {
ID: { editable: false, nullable: false, type: "string" },
LINK: { editable: true, nullable: true, type: "string" },
},
}
}
},
transport: {
read: {
url: "/getTest",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
},
destroy: {
url: "/Services/Services.asmx/removeTree",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
data: { "id": deleteId }
},
parameterMap: function (data, type) {
if ((type == "read") || (type == "update") || (type == "create") || (type == "destroy")) {
return JSON.stringify(data);
} else {
return data;
}
}
}
});
$("#treeview").kendoTreeView({
dataSource: treeMenu,
loadOnDemand: false,
expanded: true,
dataValueField: "id",
dataTextField: ['LINK'],
template: kendo.template($("#treeview-template").html()),
}).data("kendoTreeView");}
Thanks

e.slice is not a function in ASP.NET

I have a asp.net application where i have kendo ui treeview in aspx page. on document ready, i am calling a method in the aspx page for the data. The kendo treeview is not loading the data dynamically. It only shows the loading indicator. When we provide the same json data in aspx page itself, it works fine.
Here is the code
[System.Web.Services.WebMethod]
public static string MakeTreeData()
{
return "[{ text: \"Node1\", items: [{text:\"Child1\"},{text:\"Child2\"},{text:\"Child3\"}]}]";
}
script
var $jQuery2_1 = jQuery.noConflict(true);
$jQuery2_1(document).ready(function () {
$jQuery2_1.ajax({ url: "Default.aspx/MakeTreeData",
contentType: "application/json; charset=utf-8",
type: "post",
success: function (result) {
var viewModel = new kendo.data.HierarchicalDataSource({
data: JSON.parse(result.d),
schema: {
model: {
children: "items"
}
}
});
$jQuery2_1("#treeview").kendoTreeView({
dataSource: viewModel,
dataTextField: "text"
});
},
error: function (e) {
console.log(e);
}
});
});
Thanks
Updating the method and script like below solved the issue
MakeTreeData
[System.Web.Services.WebMethod]
public static string MakeTreeData()
{
JavaScriptSerializer js = new JavaScriptSerializer();
var parentNodes = new List<Node>();
var parent = new Node() { Id = "1", Text = "Parent 1", Nodes = new List<Node>() };
var child = new Node() { Id = "2", Text = "Child 1", Nodes = new List<Node>() };
parent.Nodes.Add(child);
parentNodes.Add(parent);
return js.Serialize(parentNodes);
}
Script
<div class="demo-section k-content">
<div id="treeview"></div>
</div>
<script>
$(document).ready(function () {
$.ajax({
url: "Default.aspx/MakeTreeData",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (result) {
var jsonData = JSON.parse(result.d);
var viewModel = new kendo.data.HierarchicalDataSource({
data: JSON.parse(result.d),
schema: {
model: {
children: "Nodes"
}
}
});
$("#treeview").kendoTreeView({
dataSource: viewModel,
dataTextField: "Text"
});
},
error: function (e) {
console.log(e);
}
});
});
</script>

MVC post with data and return json data

I have a controle like this
public JsonResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
I need to get that by following json by ajax request
var sizes = [];
$.ajax({
type: 'POST',
async: false,
data: { 'Id': selectedId },
url: "/<Controler name>/GetSizes",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
return false;
},
success: function (result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}
});
But this give me an Server error. How can i fix this.
replace your
url: "/<Controler name>/GetSizes",
by
url: "#Url.Action("GetSizes", "Controller_Name"),
and is you Ajax will have to be
async: false?
then try to use this as your Action
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
Also, try to put a break point on your action and see in debug mode if your Ajax reaches your Action.
this my demo, you can do the same:
$.ajax({
url: '#Url.Action("CheckCity", "BookingStarts")',
data: { packageId: packageid, cityId: valuecities[valuecities.length - 1] },
type: 'POST',
dataType: 'json',
success:
function(result) {
if (result.Status == true) {
$('#CheckoutDateHotel_#item.CityId').val(result.Date);
}
}
});
in controller :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CheckCity(int packageId, int cityId)
{
var packageCityModel = PackageDetails.GetPackageCitiesByPackageId(packageId).OfType<HMSService.PackageCity>();
var package = new PackageReservationMasterDal();
var itemPackage = package.GetPackageDetailByPackageId(packageId);
var result = "";
var city = packageCityModel.FirstOrDefault(x => x.CityId == cityId);
if (city != null)
{
result = itemPackage.TravelDateFrom.AddDays(city.NoOfNights).ToShortDateString();
}
return Json(new { Status = true, Date = result });
}
See the problem here is that you have not stringified your Data Transfer Object(DTO).
A cleaner approach will be this.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.0/json3.js"></script>
<script type="text/javascript">
var sizes = [];
var DTO = { 'Id': selectedId };
$.ajax({
type: 'POST',
async: false,
data: JSON.stringify(DTO),
url: "#Url.Action("GetSizes", "Home")",
dataType: 'json',
contentType: 'application/json'
}).done(function(result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}).fail(function(xhr) {
alert('Error: ' + xhr.statusText);
return false;
});
</script>
Please note the use of
JSON.stringify
#Url.Action helper
jqXHR.done(function( data, textStatus, jqXHR ) {});
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
Also you are using async=false which I guess is to grab all the sizes before exiting from the function. jQuery.deferred will be an interesting read.

how to pass an array of strings from jQuery to controller

How can I pass an array of strings to a controller in asp.net mvc4?
Here is my code
jQuery:
function FnSaveAnalyses(){
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
alert(checked); // it shows all the records without problem
var url = urlBiologieDemande + "Save";
$.post(
url,
data = { values: checked},
traditional= true,
success = function (data) {
DataSaved();
});
}
Controller
public ActionResult save(string[] values)
{
//Traitement
}
When debugging, I get null values.
POST IT AS JSON array.
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
var url = urlBiologieDemande + "Save";
$.ajax({
type: 'Post',
dataType: 'json',
url: url ,
data: JSON.stringify(values:checked),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
}
});
then get the JSON in the Controller
and Parse it ..
see this

Categories