Use Angular js API with ASP.net webForms - asp.net

I am using angular js with Asp.net webforms. I want to retrieve data from database using angular js API. All I have seen on google or any tutorial , uses angular js API's with Asp.net MVC .
My question is: Can we use angular js API with Asp.net web Forms?
If yes, then method will be the same as in Asp.net MVC?
Further I know angular js is for SPA(single page app) and it has Models views and controllers.

Yes, you could.
But I really really don't recommend it. It might be extremely hard to ensure they are not stepping in each other toes, because they both work by enhancing the HTML.
My recommendation is that you start moving your business logic from the Web forms code behind into Service classes, so that you can expose the business logic via [WebMethods]. You could add the WebMethods to the pages but it would be way better if you could add a REST web service endpoint using WebAPI.
Think of an angular SPA as completely independent from the server technology, all you need for Angular to work with the server is an HTTP API, preferably one that returns JSON.

Hi you can use angular with web forms, and you can do single page application also by using $HTTP service in angular.
i have written one ajax call by using web form.
<script type="text/javascript" ><src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.ButtonClick = function () {
var post = $http({
method: "POST",
url: "Default.aspx/GetCurrentTime",
dataType: 'json',
data: { name: $scope.Name },
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
$window.alert(data.d);
});
post.error(function (data, status) {
$window.alert(data.Message);
});
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Name:
<input type="text" ng-model="Name" />
<br />
<br />
<input type="button" value="Submit" ng-click="ButtonClick()" />
</div>

Related

How to provide initial data for client side javascript?

I just wonder if there was a new way to provide an initial data (json) for client side processing? I'm using ASP.NET Core MVC and I try to avoid an initial ajax request for data.
Currently I can render the Model into a json data within my asp.net view:
<script>
var serverData = #Json.Serialize(Model); //List<TextItem>
</script>
Then I can access that serverData in my client script (VueJs, .vue component file):
<template>
<ul>
<li v-for="item in list">{{item.text}}</li>
</ul>
</template>
<script>
export default {
data: function () {
return {
list: serverData
}
}
};
</script>
Solution works fine but I don't really like to render raw data into the page source. Is there any more elegant way to provide an inital data without any additinal (ajax) request to the server?
Edit:
I found an article about the concept (it uses angular):
https://blog.mariusschulz.com/2014/03/25/bootstrapping-angularjs-applications-with-server-side-data-from-aspnet-mvc
Is it still the best way to pre-render data on server side?

Json get not working through azure but working locally

I have created a asp.net webapi and hosted it through azure.
This works fine when I run host/api/carparks. It also works when I run an ODATA query string
host/api/carparks?$Filter%20eq%20%27Liverpool%27
Google chrome returns the results as JSON as I want them.
The problem I am having is, I need to create a "Client" application to visualize my data. I have created a really simple for loop to return my data for testing purposes, once I have data returned I can start creating my application.
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function getStations() {
var town = document.getElementById("town").value;
var stationList = "<p>";
var uri = "http://localhost:38852/api/carparks?$filter=Town%20eq%20%27" + town + "%27";
$.getJSON(uri,
function (data) {
$('#here_data').empty(); // Clear existing text.
// Loop through the list of products.
$.each(data, function (key, val) {
stationList += val.Name + '<br />';
});
stationList += "</p>";
document.getElementById("here_data").innerHTML = stationList;
});
}
$(document).ready(getStations);
</script>
</head>
<body onload="getStations()">
<h1>Stations API</h1>
<p>Enter town</p>
<input type="text" id="town" value="Derby" />
<input type="button" value="Find Stations" onclick="getStations()" />
<div id="here_data">
<p>Car parks go here</p>
</div>
</body>
</html>
My client app works perfectly when I run my web api locally but when I change the getJSON request URI to my azure one (Which works in the browser!) nothing happens.
I have tried uploading my client app to azure and testing it that way but nothing :(
Is there any Azure settings that need to be changed?
Looks very much like a cross-origin issue.
The issue does not occur when you call the Service directly in your browser but only when you issue an Ajax call from a different domain (localhost vs. *.azurewebsites.net).
If you want to access your Web Api service with an Ajax call from a different domain you need to enable Cross Origin Resource Sharing (CORS).
A detailed article is found here:
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Quoted from the link:
Install-Package Microsoft.AspNet.WebApi.Cors
Open the file App_Start/WebApiConfig.cs. Add the following code to the
WebApiConfig.Register method.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Next, add the [EnableCors] attribute to the TestController class:
using System.Net.Http; using System.Web.Http; using
System.Web.Http.Cors;
namespace WebService.Controllers
{
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
For the origins parameter, use the URI where you deployed the
WebClient application. This allows cross-origin requests from
WebClient, while still disallowing all other cross-domain requests.
Later, I’ll describe the parameters for [EnableCors] in more detail.
Do not include a forward slash at the end of the origins URL.
Thanks to #viperguynaz and #florian I have fixed my issue. I changed the CORS option in Azure portal. (When I first did it I didn't remove the forward slash at the end of the URL). I removed the slash and it works.
I have also used the info given by #florian to help me understand CORS more.
Thanks again
1 happy joe :)

Angularjs routes conflicting with MVC 5 routing

I am developing a mini SPA, using angular, inside my ASP.Net MVC 5 application. Basically I want to use this mini SPA for onboarding/registration workflow, and use ASP.Net MVC views and routes for other functionality.
For Onboarding mini SPA I have defined an MVC route:
routes.MapRoute(
name: "Onboarding",
url: "onboarding/{*catchall}",
defaults: new { controller = "Onboarding", action = "Create" }
);
The Angular configuration looks like:
(function () {
var app = angular.module('app', ['ngRoute']);
app.config(function ($routeProvider, $locationProvider) {
$routeProvider.caseInsensitiveMatch = true;
$routeProvider.when('/onboarding', { templateUrl: '/app/Views/CreateShop.html', controller: 'onboardingController' })
.when('/onboarding/add-product', { templateUrl: '/app/Views/AddProduct.html', controller: 'onboardingController' })
$locationProvider.html5Mode(true);
});}());
The Create.chtml uses acts as a container/entry point for this mini SPA.
<div ng-controller="onboardingController">
<div ng-view></div>
</div>
#section scripts {
#Scripts.Render("~/bundles/angularOnboarding")
}
PROBLEM: When I am inside the mini SPA my navigation links/routes break e.g. navigation to contact page or about page (MVC Views) doesn't work. Angular seems to handling all routing requests. Also, navigation from an anchor tag which navigates to some MVC route doesn't work.
Putting the url in the browser works.
How do I make this work for my hybrid scenario?
Would really appreciate any suggestions or solution, Thanks.

Trigger.io + Angular.js and updating a view after calling forge.ajax

Having a problem, and so far couldn't get any solutions for seemingly similar SO questions to work. Problem is this:
Using Trigger.io's forge.ajax, my Angular.js view is not updated after the data is returned. I realize this is because forge.ajax is an asychronous function, and the data is returned after the view has already been displayed. I have tried to update the view by using $rootScope.apply(), but it doesn't work for me as shown in the many examples I have seen.
See the Controller code below:
function OfferListCtrl($scope) {
$scope.offers = [];
$scope.fetchOffers = function(callback) {
$scope.offers = [];
var successCallback = function(odataResults) {
var rawJsonData = JSON.parse(odataResults);
var offers = rawJsonData.d;
callback(offers);
};
var errorCallback = function (error){
alert("Failure:" + error.message);
};
forge.request.ajax({
type: 'GET',
url: 'https://www.example.com/ApplicationData.svc/Offers',
accepts: 'application/json;odata=verbose',
username: 'username',
password: 'password',
success: successCallback,
error: errorCallback
});
};
$scope.fetchOffers(function(offers) {
$scope.offers = offers;
forge.logging.info($scope.offers);
});
}
All the code there works fine, and $scope.offers gets populated with the Offer data from the database. The logging function shows the data is correct, and in the correct format.
I have tried using $rootScope.apply() in the logical places (and some illogical ones), but cannot get the view to update. If you have any ideas how I can get this to work, I would greatly appreciate it.
Edit: Added HTML
The HTML is below. Note the button with ng-click="refresh()". This is a just a workaround so I can at least see the data. It calls a one-line refresh function that executes $rootScope.apply(), which does update the view.
<div ng-controller="OfferListCtrl">
<h1>Offers</h1>
<ul>
<li ng-repeat="offer in offers">
<p>Description: {{offer.Description}}<br />
Id: {{offer.Id}}<br />
Created On: {{offer.CreatedOn}}<br />
Published: {{offer.Published}}<br />
</p>
</li>
</ul>
<input type="button" ng-click="refresh()" value="Refresh to show data" />
</div>
You need to change
$scope.fetchOffers(function(offers) {
$scope.$apply(function(){
$scope.offers = offers;
});
forge.logging.info($scope.offers);
});
It is because all changes to the $scope has to be made within the angular scope, in this case since you are calling ajax request using forge the callback is not executing within the angular framework, that is why it is not working.
You can use $scope.$apply() in this case to execute the code within angular framework.
Look at the $apply() methods doc
$apply() is used to execute an expression in angular from outside of
the angular framework. (For example from browser DOM events,
setTimeout, XHR or third party libraries). Because we are calling into
the angular framework we need to perform proper scope life-cycle of
exception handling, executing watches.
do this
function MyController($scope, myService)
{
myService.fetchOffers(data){
//assign your data here something like below or whateever
$offers = data
$scope.$apply();
}
});
Thanks
Dhiraj
When I do that I have an error like : "$digest already in progress"...
I'm Working with $q...
Someone knwo how I can resolve this issue ?
yes, this is caused where ur data comes fast enough and angular has not finished his rendering so the update cant update "outside" angular yet.
so use events:
http://bresleveloper.blogspot.co.il/2013/08/angularjs-and-ajax-angular-is-not.html

Jquery Ajax Call does not Call the function in .CS file

Always i get the alert in the "error". When i debugged i get the type,url as undefined. can anyone help me why that method is not getting called??
$(document).ready(function () {
$("#btnajaxcall").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/jQueryAjaxCalledMethod",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: 'json',
success: function () { alert('success') },
error: function () { debugger; alert('failure'); return false; }
});
});
});
[WebMethod]
public void jQueryAjaxCalledMethod()
{
//SOME CODE HERE
}
If im correct you should be using static method for these purposes, so function in your code behind should look like this
[WebMethod]
public static void jQueryAjaxCalledMethod()
{
//SOME CODE HERE
}
If you still get some errors take a look on this guy blog Encosia maybe you'll find there a solution
The jquery Ajax method is going to post your data in json format using the plain html protocol. ASP.NET will be expecting to unwrap a SOAP request to pass to the webmethod. Thus the error. You should use an MVC action instead, as suggested in one of the comments.
EDIT:On further investigation ASP.Net has an attribute that will allow the web method to be called:
[System.Web.Script.Services.ScriptService].
Use this attribute on the class and it might solve your problem.
Hi all i just used the jquery file hosted with google.
It worked out fine.
Previously i was using the jquery version 1.7.1 that i had downloaded and stored in my local. I also saw a lot of questions in the forum that this particular ajax call is quite not happening properly with .NET 4. I am not sure and forgive me if i am wrong but i do have a feeling that 1.7.1 in this case is not properly working with ASP.NET 4.
P.S -> I used this in the script tag -->
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"

Resources