I have a project which contains all plain html pages with angularJS and one .aspx page. I need some data in list/json format in my aspx page's code behind from angular controller. Can this be done ? If yes, please guide.
I'm new to angular, please be kind.
Scenario is I want to download the current html page as pdf. I found jspdf but for some reason it is not working in IE, works in chrome.
So, I am putting a workaround where I can do this with aspx page, I just need data there.
//Download PDF
$scope.PDFDownload = function () {
window.open('ReportPage.aspx');
//need to send list/json data to aspx code behind here.
}
I need some data in list/json format in my aspx page's code behind
from angular controller.
If you want to send/receive data to/from ASPX Web Form, you want to use WebMethod.
using System.Web.Script.Serialization;
namespace DemoWebForm
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostJson(string firstName, string lastName)
{
return new JavaScriptSerializer().Serialize(
"Hello, " + lastName + ", " + firstName + "!");
}
}
}
Usage
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body ng-app="demoApp">
<form id="form1" runat="server" ng-controller="DemoController">
<pre>{{user}}</pre>
<button type="button" onclick="ajaxPostData();">Post Data Ajax</button>
<button type="button" ng-click="ngPostData()">Post Data Angular</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
function ajaxPostData() {
var user = { firstName: "John", lastName: "Doe" };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postjson") %>',
data: JSON.stringify(user),
contentType: "application/json",
success: function (msg) {
console.log(msg.d);
}
});
}
var demoApp = angular.module('demoApp', [])
.controller('DemoController', function DemoController($scope, $http) {
$scope.user = { "firstName": "John", "lastName": "Doe" };
$scope.ngPostData = function () {
$http.post('<%= ResolveUrl("~/default.aspx/postjson") %>', $scope.user)
.then(function (result) {
console.log(result.data.d);
});
}
});
</script>
</form>
</body>
</html>
Screen shot
Related
This is my model file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ConsumeJson.Models
{
public class ProductModel
{
public List<Product> findAll()
{
List<Product> result = new List<Product>();
result.Add(new Product { Id = "p01", Name = "Product 1", Price = "100", Quantity = "1" });
result.Add(new Product { Id = "p02", Name = "Product 2", Price = "200", Quantity = "2" });
result.Add(new Product { Id = "p03", Name = "Product 3", Price = "300", Quantity = "3" });
return result;
}
public Product find(string id)
{
return findAll().Single(p => p.Id.Equals(id));
}
}
}
This is my HTML file.
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<meta charset="utf-8" />
<script src="Scripts/jquery-3.3.1.min.js"></script>
<script src="Scripts/jquery-3.3.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<title>My Client</title>
</head>
<body ng-controller="productController">
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr ng-repeat="product in result">
<td>{{product.Id}}</td>
<td>{{product.Name}}</td>
</tr>
</table>
<script type="text/javascript">
var myapp = angular.module('myapp', []);
myapp.controller('productController', function ($scope, $http) {
$http(
method: 'GET',
url:'http://localhost:53204/api/product').success(function (response) {
$scope.result = response;
})
})
</script>
</body>
</html>
I want to create product's table with informations but hen i run it as localhost it never display the product's id or name.
It stays like this way. {{Product.Id}} {{Product.Name}} How can i solve this?
You need to change it to using .then()
$http({
method: "GET",
url: "http://localhost:53204/api/product"
}).then(function mySucces(response) {
$scope.result = response.data;
}, function myError(response) {
});
May have many reason.
Check your scope inserted, are you sure that you send ProductId to server side with Http request?.
it's better that use of ngModel instead of dubble braces. check this
and the Important issue is, if your model like this:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
when your API wants to return your response, convert data to Json, attention that your model is KebabCase but your Json in camelCase, but in your html you use of KebabCase.
If all of this issues not work, check your network and check response of your request in response tab, Is there any response or any Ids?
GoodLuck.
I want to synthesize a Json array of objects for the auto complete from server side, and for now I hard coded something like below when page loads but it didn't work. However when I changed it like "local: [{ name: 'Foo' }, { name: 'FFoo' }, { name: 'Ah' }]" in JS file, it works.
Is it possible to render the "local" data from server side and how can I make a Json string using Vb.net?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
hdTypeahead.Value = "[ { 'name': 'ah'},{ 'name': 'ba'},{ 'name': 'cha'} ]"
End Sub
var dataSetBloodhound = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
//local: $('#<%= hdTypeahead.ClientID %>').val()
local: [{ name: 'Foo' }, { name: 'FFoo' }, { name: 'Ah' }]
});
dataSetBloodhound.initialize();
$('input').tagsinput({
freeInput: true,
typeaheadjs: {
name: 'dataSetBloodhound',
displayKey: 'name',
valueKey: 'name',
source: dataSetBloodhound.ttAdapter()
}
});
<link href="https://rawgit.com/timschlechter/bootstrap-tagsinput/master/src/bootstrap-tagsinput.css" rel="stylesheet"/>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<script src="http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/dist/bootstrap-tagsinput.min.js"></script>
<input type="text" value="Amsterdam,Washington,Sydney,Beijing,Cairo" data-role="tagsinput" />
<input runat="server" id="hdTypeahead" type="text" value="" style="display:none"/>
try
local: JSON.parse($('#<%= hdTypeahead.ClientID %>').val())
or please open console log to the same page and get exact value of this element from $('#<%= hdTypeahead.ClientID %>')
The problem is not with your data coming from server side it is actually parsing of java script array to a variable. Your data is stored in string format in hdTypeahead control's val, so in order to make it an array you have to use some parser present in java script. I have implemented the code as follows:
WebForm1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="tempApp2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input id="hidTypeAhead" type="hidden" runat="server" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var typeAhead = JSON.parse($('#<%= hidTypeAhead.ClientID %>').val());
console.log(typeAhead.data);
</script>
</body>
</html>
WebForm1.aspx.vb
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace tempApp2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
hidTypeAhead.Value = #"{""data"":[{ ""name"": ""Foo"" }, { ""name"": ""FFoo"" }, { ""name"": ""Ah"" }]}";
}
}
}
So first understand that you have array data in string not some object while JS have JSON.parse() method which can parse string to JS object. So you simply have to add your array to an object within the string as I have done as follows:
hidTypeAhead.Value = #"{""data"":[{ ""name"": ""Foo"" }, { ""name"": ""FFoo"" }, { ""name"": ""Ah"" }]}";
I have added my array in data property of the JS object. The next part is to parse it using JSON.parse() the following code will do the needy:
var typeAhead = JSON.parse($('#<%= hidTypeAhead.ClientID %>').val());
So that's it you will get your array in typeAhead variable's "data" property which you can then assign to your property "local" as
local: typeAhead.data
Or directly
local: JSON.parse($('#<%= hidTypeAhead.ClientID %>').val()).data;
Hope it helps
I have an $.post() and i want receive the data into my controller, how could i do that?
jQuery
$.post($('#url').val() + "Dashboard/getApi", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
vvvvvvvvvvvvvvvvvvv this is my url vvvvvvvvvvvvvv
$('#url').val() + "Dashboard/getApi" = "http://127.0.0.1/M2MWare/Dashboard/getApi"
And this is my controller
function getApi()
{
$valores = $this->input->post();
// print_r($valores);
return json_encode($valores);
}
this returns me an empty array, i tried with different url, data and nothing why?
Codeigniter 3.1.0 running on WampServer.
The Dashboard Controller
<?php
defined('BASEPATH') OR exit( 'No direct script access allowed' );
class Dashboard extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('post_view');
}
function getApi() {
$valores = $this->input->post();
echo json_encode($valores);
}
}
The View post_view.php This is Very Bare Bones for simplicity.
<html lang="en">
<head>
<title>Post Me</title>
</head>
<body>
<form>
<input type="hidden" id="url" value="http://ci310tut.com/">
</form>
<script src="<?= base_url('assets/js/jquery.min.js'); ?>"></script>
<script>
$(document).ready(function () {
console.log('We should be seeing an alert popup');
$.post($('#url').val() + "Dashboard/getApi", {name: "John", time: "2pm"})
.done(function (data) {
alert("Data Loaded: " + data);
});
});
</script>
</body>
</html>
And from the above I get an alert screaming at me each time I perform a page refresh with the provided data being displayed.
So you might want to check the above against what you have.
Hello I'm new to MVC and AJAX.
I have a problem sending input data from view to controller.
What is the wrong thing in this code ? :
Thanks in advance.
Head :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
View :
<div id="inputdiv">
<p>Display name: <input type="text" id="name1" /> </p>
<p><button id="submitbutton">Submit</button></p>
</div>
<script type="text/javascript" language="javascript">
$(function () {
$("#submitbutton").click(function () {
var nameEntered = $("#name1").val()
$.post(
'<%= Url.Action("SimplePost") %>',
{ submittedName: nameEntered },
handleSuccess
);
});
});
function handleSuccess(content) {
$("#inputdiv").html(content);
$("#inputdiv").addClass("easy-notification");
}
</script>
Controller :
[HttpPost]
public ContentResult SimplePost(string submittedName)
{
string result = string.Format("Hello {0}!?", submittedName);
return new ContentResult { Content = result };
}
I have a DataList and Update Panel in my page. After implementation, I checked that the response is talking very long time after using Update panels...Here is the study material. I have a Delete Command event in Datalist and works find in the above mentioned case. I was trying to implement Delete Command using Page Methods. Any Idea how to do that?
I basically want to find hidden controls in this event and have to delete the record in `database. Any help will be highly appreciated.
Rest Services
The full application can be downloaded from:
http://sdrv.ms/LJJz1K
This sample uses rest services in ASP.Net (the same concepts can be applied to a MVC application)
The clearer advantage when using rest services vs page methods, is testability.
I will guide you step by step to configure the service:
You need the following references:
System.Web.ServiceModel.dll
System.Web.ServiceModel.Activation.dll
System.Web.ServiceModel.Web.dll
Nuget packages:
jQuery
jQuery plugins:
jQuery Block UI (it’s available as a single script file)
Service info
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebInvoke(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "/DeleteFromService",
Method = "DELETE")]
void Delete(int id);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public void Delete(int id)
{
// delete your product
// simulate a long process
Thread.Sleep(5000);
}
}
In Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
RouteTable.Routes.Add(new ServiceRoute("",
new WebServiceHostFactory(),
typeof(MyService)));
}
In web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Register scripts (they can be registered in a master page)
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js" language="javascript" ></script>
<script language="javascript" type="text/javascript" src="Scripts/jquery.blockui.1.33.js"></script>
In a ASP.Net content page (in this sample, I am using a master page)
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="button" value="Delete" id="myButton" />
</asp:Content>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" language="javascript">
function deleteFromService() {
if (!confirm("Are you sure you want to delete?")) {
return;
}
$.blockUI();
$.ajax({
cache: false,
type: "DELETE",
async: true,
url: "/DeleteFromService",
data: "3", // get your id to delete
contentType: "application/json",
dataType: "json",
success: function () {
$(document).ajaxStop($.unblockUI);
alert("done");
},
error: function (xhr) {
$(document).ajaxStop($.unblockUI);
alert(xhr.responseText);
}
});
}
jQuery().ready(function () {
$("#myButton").click(deleteFromService);
});
</script>
</asp:Content>
And that’s it, ajax commands the easy way =)