i am developing an application using angular js in which i have to populate the customer list using data in database for that i write a web method to get the data like
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getname()
{
SqlHelper sql = new SqlHelper();
DataTable dt = sql.ExecuteSelectCommand("select cust_F_name,cust_L_name from customer");
Dictionary<string, object> dict = new Dictionary<string, object>();
object[] arr = new object[dt.Rows.Count];
List<CustName> custName = new List<CustName>();
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
CustName c = new CustName();
c.cust_F_name = dt.Rows[i]["cust_F_name"].ToString();
custName.Add(c);
}
dict.Add("JsonCustomer", custName);
JavaScriptSerializer json = new JavaScriptSerializer();
return json.Serialize(dict);
//return "Rhsuhikesh";
}
}
public class CustName
{
public string cust_F_name { get; set; }
}
catch that Json data as
var DemoApp = angular.module('DemoApp', []);
DemoApp.factory('SimpleFactory', function ($http) {
return {
getCustomer: function () {
return $http.post('Home.aspx/getname', { name: "" });
}
};
});
DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function (customer) {
$scope.Customer = customer.data;
}, function (error) {
// error handling
});
});
and view it as
<html xmlns="http://www.w3.org/1999/xhtml" data-ng-app="DemoApp">
<head runat="server">
<title></title>
</head>
<body data-ng-controller="SimpleController">
<form id="form1" runat="server">
<div>
Name<input type="text" data-ng-model="Name" />{{ Name }}
<ul>
<li data-ng-repeat="customerName in Customer | filter:Name">{{ customerName }} </li>
</ul>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="Script/Home.js" type="text/javascript"></script>
</body>
</html>
and I am getting o/p as
but i want it as
data in json i have to access in name value pair but i am not understand how to do it please help me to out if it.
thanks in advance.
Since you get your results as JSON string you need to convert it to JavaScript object using angular.fromJson
For example:
DemoApp.controller('SimpleController', function ($scope, SimpleFactory) {
SimpleFactory.getCustomer().then(function (customerData) {
var customersRawObject = angular.fromJson(customerData);
}, function (error) {
// error handling
});})
Then you can do somthing like this:
$scope.customerA=customersRawObject.JsonCustomer[0];
Related
I need to get a list of innerHTML strings from a website (for example facebook) to my .NET application.
Is there a way to get results from the following function into my application (i would put this data into a list) :
var data = new Array();
for(i=0; i<document.getElementsByClassName("class-name").length;i++)
data.push(document.getElementsByClassName("class-name")[i].innerHTML);
The code above outputs exactly the data i need, now my question is if it's possible to somehow get this data into my c# list?
This is how I'd like it to look :
var JS_DATA = data; //get the js array as a variable
static List<string> data = new List<string>(); //make a new list
foreach (string str in JS_DATA)
data.Add(String.Format("{0}", str)); //add the whole js array to the list
Here is an example:
see hidden Field array_store
Client side:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var array_store;
window.onload = function () {
array_store = document.getElementById("array_store");
document.getElementById("array_disp").innerHTML = array_store.value;
};
function UpdateArray() {
var arr;
if (array_store.value == "") {
arr = new Array();
} else {
arr = array_store.value.split(",");
}
arr.push((arr.length + 1).toString());
array_store.value = arr.join(",");
};
</script>
</head>
<body>
<form id="form1" runat="server">
<span id="array_disp"></span>
<br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="UpdateArray()" />
<input type="hidden" id="array_store" name = "ArrayStore" value = '<%=this.ArrayStore %>' />
</form>
</body>
</html>
C#:
protected string ArrayStore = "";
protected void Page_Load(object sender, EventArgs e)
{
this.ArrayStore = Request.Form["ArrayStore"];
}
Hello I am beginner in mean Stack. and I have data in localstorage and I want to fetch the data from the local storage and show in html file but I don't know How to get it. on the view file.
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
when I type localStorage; into console it show
ngStorage-userData
:
"{
"_id":"5846692617e0575c0e0c2211",
"password":123456,
"email":"montyy1981#gmail.com",
"name":"digvijay12","__v":0
}"
How to get it value into the view file.I used like
<div>{{userData.email}}</div>
But it is not showing data.please help me how to fetch localstorage data and show into view file.
You can use core concept without ngStorage....
https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
localStorage.setItem("userData", $scope.Data);
$scope.storageData = localStorage.getItem("userData");
<p>{{storageData.email}}</p>
How to get the localStoragedata anywhere this is very simple we have to pass localStorage data into the controller global variable suppose
we have the data into localstorage
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
we have to define pass $localStorage.userData into the other variable after controller start.
app.controller("usercontroller",function($scope,$http, $localStorage,$location){
$scope.registeruser = $localStorage.userData;
$scope.useredit = function (d) {
var user_id = d._id;
var dataToModify;
angular.forEach($scope.dp, function (value, key) {
if (user_id == value._id) {
dataToModify = value;
$localStorage.userData = dataToModify;
console.log($localStorage.userData.name);
$location.path('/useredit');
}
});
}
});
For better understanding click this DEMO
In the controller you need to inject "ngStorage" angular.module('MyApp', ["ngStorage"]).
And add the dependency script link <script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
HTML
<html ng-app="MyApp">
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="https://cdn.jsdelivr.net/ngstorage/0.3.6/ngStorage.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="MyController">
<input type="button" value = "Save" ng-click = "Save()" />
<input type="button" value = "Get" ng-click = "Get()" />
</div>
</body>
</html>
Script.js
var app = angular.module('MyApp', ["ngStorage"])
app.controller('MyController', function ($scope, $localStorage, $sessionStorage, $window) {
$scope.Save = function () {
$localStorage.email = "xyz#gmail.com";
}
$scope.Get = function () {
$window.alert($localStorage.email);
}
});
Hope it will be usefull for you.
I'm receiving the following error when I load my page (on alert box)
DataTables warning: table id= entry-grid - Ajax error. For more information about this eror, please see http://datatables.net/tn/7
What is wrong. I've run the web application in debug and my C# works fine, records are taken from the DataBase, but something goes wrong with the Angular js
When i debug in the browser the entire code after var app = angular.module('MyApp', ['datatables']); is just being ignored. This is the error in the console POST http://localhost:10575/teachers/getdata 500 (Internal Server Error)
Here is my MVC Controllers
public ActionResult Index()
{
return View();
}
public ActionResult getData()
{
//Datatable parameter
var draw = Request.Form.GetValues("draw").FirstOrDefault();
//paging parameter
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
//sorting parameter
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
//filter parameter
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
List<tblTeacher> allCustomer = db.tblTeachers.ToList();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
//Database query
using (RSEntities dc = new RSEntities())
{
var v = (from a in dc.tblTeachers select a);
//search
if (!string.IsNullOrEmpty(searchValue))
{
v = v.Where(a =>
a.FirstName.Contains(searchValue) ||
a.SecondName.Contains(searchValue) ||
a.Title.Contains(searchValue) ||
a.TDepartment.Contains(searchValue)
);
}
//sort
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir)))
{
//for make sort simpler we will add Syste.Linq.Dynamic reference
v = v.OrderBy(sortColumn + " " + sortColumnDir);
}
recordsTotal = v.Count();
allCustomer = v.Skip(skip).Take(pageSize).ToList();
}
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal = recordsTotal, data = allCustomer });
}
Now the Angular Js
/// <reference path="angular.js" />
/// <reference path="angular.min.js" />
/// <reference path="angular-route.min.js" />
/// <reference path="angular-route.js" />
var app = angular.module('MyApp', ['datatables']);
app.controller('homeCtrl', ['$scope', '$http', 'DTOptionsBuilder', 'DTColumnBuilder',
function ($scope, $http, DTOptionsBuilder, DTColumnBuilder) {
$scope.dtColumns = [
//here We will add .withOption('name','column_name') for send column name to the server
DTColumnBuilder.newColumn("FirstName", "Име").withOption('name', 'FirstName'),
DTColumnBuilder.newColumn("SecondName", "Фамилия").withOption('name', 'SecondName'),
DTColumnBuilder.newColumn("Title", "Титла").withOption('name', 'Title'),
DTColumnBuilder.newColumn("TDepartment", "Факултет").withOption('name', 'TDepartment'),
]
$scope.dtOptions = DTOptionsBuilder.newOptions().withOption('ajax', {
dataSrc: "data",
url: "/teachers/getdata",
type: "POST"
})
.withOption('зареждане', true) //for show progress bar
.withOption('serverSide', true) // for server side processing
.withPaginationType('full_numbers') // for get full pagination options // first / last / prev / next and page numbers
.withDisplayLength(10) // Page size
.withOption('aaSorting', [0, 'asc']) // for default sorting column // here 0 means first column
}])
Finally the View
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.js"></script>
<script src="~/Scripts/DataTables/jquery.dataTables.min.js"></script>
<script src="~/Scripts/angular.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/DataTables/css/jquery.dataTables.css" rel="stylesheet" />
<link href="~/Content/DataTables/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-datatables/0.5.5/angular-datatables.js"></script>
<script src="~/Scripts/myApp.js"></script>
<div ng-app="MyApp" class="container">
<div ng-controller="homeCtrl">
<table id="entry-grid" datatable="" dt-options="dtOptions" dt-columns="dtColumns" class="table table-hover"></table>
</div>
</div>
I'm trying to call a COM C# Object from javascript code and get an object that doesn't contain the COM object functions.
I created a setup project for the C# COM library. The library is signed for COM interop, and the setup project output is signed for COM register on the machine it deployed at.
I see that the TLB is properly exported.
C# Code:
using System;
using System.Runtime.InteropServices;
namespace YaronTestCOM
{
[Guid("BD145EEC-ACAC-4FDB-B766-0F15CE07990F")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IComEvents))]
public class YaronComObject : IComObject, IObjectSafety
{
[ComVisible(false)]
public delegate void YaronFirstEventHandler(string args);
public event YaronFirstEventHandler YaronFirstEvent;
public int YaronFirstComCommand(string arg)
{
if (YaronFirstEvent != null)
YaronFirstEvent(arg);
return (int)DateTime.Now.Ticks;
}
public void Dispose()
{
}
}
[Guid("A3576AA4-9DE0-422D-BAA3-3FFB862E8007")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[ComVisible(true)]
public interface IComObject
{
[DispId(0x10000001)]
int YaronFirstComCommand(string arg);
[DispId(0x10000002)]
void Dispose();
}
[Guid("B551EC8B-4D19-4781-938C-9E50E70D37CD")]
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IComEvents
{
[DispId(0x00000001)]
void YaronFirstEvent(string args);
}
}
HTML+Javascrip Code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<object id="publisher" name="publisher" classid="clsid:BD145EEC-ACAC-4FDB-B766-0F15CE07990F"></object>
<title>Sender Test</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var msgTxt = $("#msgTxt");
$("#btnSend").click(function () {
var msg = msgTxt.val();
//publisher.YaronFirstComCommand is undefined!!!
var result = publisher.YaronFirstComCommand(msg);
alert('The message ' + msg + 'has been sent and returned ' + result);
});
});
</script>
</head>
<body>
<div>
<input type='text' id='msgTxt' />
<input type='button' value='Send Message' id='btnSend' />
</div>
</body>
Any ideas?
I am new in Angular JS and learning it. I have a div and load data from json on startup with controller with following code but I want to reload it again when json object changed after performing specific action.
index.html
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html ng-app="ezpf" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="lib/angular.js"></script>
<script src="lib/jquery.min.js"></script>
</head>
<body onload="EZPF.Application.initialize()">
<div id="btn-import" class="my-button button-small" onClick="EZPF.Application.openFile(this)">
<span class="button-title">Import</span>
<span class="button-help">This button will do something else.</span>
</div>
<div class="page" id="pro" ng-controller="ProductsListCtrl as store">
<div ng-repeat="product in store.products.Products">
{{product.Title}}
</div>
</div>
</body>
</html>
myAngular.js
(function()
{
var app = angular.module('ezpf', []);
app.controller('ProductsListCtrl',['$scope', function($scope)
{
this.products = EZPF.Application.getProducts();
$scope.reload = function()
{
$scope.products = EZPF.Application.getProducts();
};
}]);
})();
In following javascript file I am opening JSON file and reload products object with new data. After updating with new JSON file contents I have to reload data. I have tried to call reload from controller but its not working. Please help me, thanks in advance.
application.js
var EZPF;
if (!EZPF)
EZPF = {};
if (!EZPF.Application)
EZPF.Application = {};
EZPF.Application =
{
products: [],
getProducts: function()
{
if (this.products.length == 0)
{
this.products =
{
"Products": [
{
"Title": "default name"
....
}]
}
}
return this.products;
},
openFile: function()
{
var docsDir = air.File.documentsDirectory;
try
{
var jsonFilter = new air.FileFilter("JSON Files", "*.json");
docsDir.browseForOpenMultiple("Select JSON Files", [jsonFilter]);
docsDir.addEventListener(air.FileListEvent.SELECT_MULTIPLE, filesSelected);
}
catch (error)
{
air.trace("Failed:", error.message)
}
function filesSelected(event)
{
air.trace(event.files[0].nativePath);
var myFile = new window.runtime.flash.filesystem.File();
var file = myFile.resolvePath(event.files[0].nativePath);
var fileStream = new air.FileStream();
fileStream.open(file, air.FileMode.READ);
this.products = fileStream.readMultiByte(fileStream.bytesAvailable, air.File.systemCharset);
fileStream.close();
air.trace(products);
$('#pro').reload();
}
}
};
You are using the controller as (ng-controller="ProductsListCtrl as store") syntax, so you have to assign the variables to the controller itself (this) instead of the $scope:
var vm = this;
vm.products = EZPF.Application.getProducts();
vm.reload = function()
{
vm.products = EZPF.Application.getProducts();
};
To reload the data:
<div class="page" id="pro" ng-controller="ProductsListCtrl as store">
<div ng-repeat="product in store.products.Products">
{{product.Title}}
</div>
<!-- Button for reloading the data -->
<button ng-click="store.reload()">Reload Data</button>
</div>
JSFIDDLE