I am currently developing a page which is (nearly) fully inline-editable with CKEditor. So after the user has finished editing I want to get the plain HTML Code, remove the editor controls and send the result via eMail. This disqualifies the WebRequest-Method as this "reloads" the page. Is there an option to get the CURRENT html from the page in a string?
Most likely you have to do this by AJAX. Get the contents of the HTML to a JavaScript variable, then POST the variable to your backend (where you now have the WebRequest). Try something like this if you use jQuery:
var markup = document.documentElement.innerHTML;
alert("Submitting: " + markup"); // big alert...
$.ajax({
type: "POST",
url: "path/to/HTML_handler.aspx",
data: { html: markup }
})
.done(function(msg) {
alert("Data Saved: " + msg);
});
Then in your backend read the posted html variable a vomit it into a backend.
Edit 11.9.2014
I'm an MVC guy myself, but the classic ASP.net way of doing this I think is something like this: in your aspx view, add a button, such as this: <button id="Derp">I love ponies</button>. Add a reference to jQUery: <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> (I'm using the Google CDN here). Then bind a click event to the button:
<script type="text/javascript">
$(function() {
var btn = $('#Derp');
btn.click(function() {
var markup = document.documentElement.innerHTML;
alert("Submitting...");
$.ajax({
type: "POST",
url: "AJAXRequest.ashx", // Important that this points to the right file...
data: { html: markup }
})
.done(function(msg) {
alert("Data Saved: " + msg);
});
});
});
</script>
Then create a backend handler (Google for more tutorials) that goes something like this:
AJAXRequest.asgx (yeah, just one line):
<%# WebHandler Language="C#" CodeBehind="AJAXRequest.ashx.cs" Class="WebApplication1.AJAXRequest" %>
AJAXRequest.ashx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace WebApplication1
{
public class AJAXRequest : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Not sure which one to use here, try both
string html1 = context.Request["html"];
string html2 = context.Request.Form["html"];
// Do whatever you want with the html...
context.Response.Write("OMG I just found: " + html1);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Yeah, this code is very much untested, but I think you get the gist of it.
Related
I am trying to pass data to server in angular using webapi. Thanks to people on the forum I was able to fill 1 drop down based on another using entity framework and angular. The next thing I wanted to figure out was how to pass screen data back to the server using webapi.
When the angular code is being called I am getting an error: badreq 'Http request configuration must be an object'
This error shows in the $http
I found an example online where it shows the ability of creating a parent model used by each of the html controls. In the case of the example online they were using textboxes, but I am using select lists, but I assume this should also work.
Can someone please tell me what I am doing wrong?
I appreciate it!!
FOLLOW UP: The problem I am having at this point seems to be that Data in the Angular saveattributecontroller states as UNDEFINED. So the issue I don't believe at this point is the call to the webapi, but the data not being passed from "Detail" in the HTML.
FOLLOW UP 2: based on Lorenzo's comment below. By putting the attributevaluecontroller around the submit button, I can now see the data passed to the saveattributecontroller in the attribute.js which is good. I also realized I needed to reference Data.A and Data.V in the saveattributecontroller. But now it seems the call to the WebAPIAttribute controller is not happening. I tried both the way I originally had and the other way that was suggested earlier yet the call to the controller never seems to go through. Can anyone help me with that?
Follow UP 3: The error I am finding as I step through the angular javascript is Resource can't be found. So I am assuming it is not finding the webapi controller for some reason. It's probably something very simple, but I am not seeing it.
var myapp = angular.module('attributeapp', []);
myapp.controller('attributecontroller', function ($scope, $http) {
$http.get('/Attribute/AttributeIndex/').then(function (response) {
$scope.Attributes = response.data;
})
})
myapp.controller('attributevaluecontroller', function ($scope, $http) {
$scope.getattributevalues = function (id)
{
$http.get('/Attribute/getattributevalues/' + id).then(function (response) {
$scope.A = id;
$scope.AttributeValues = response.data;
})
}
})
myapp.controller('saveattributecontroller', function($scope, $http){
$scope.attributesave = function (Data) {
var GetAll = new Object();
GetAll.AttributeKey = Data.AttributeKey;
GetAll.AttributeValueKey = Data.AttributeValueKey;
$http({
url: "WebAPIAttribute/attributesave",
dataType: 'json',
method: 'POST',
data: GetAll,
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.value = response;
})
.error(function (error) {
alert(error);
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/angular.js"></script>
<script src="Scripts/attribute.js"></script>
</head>
<body data-ng-app="attributeapp">
<div data-ng-controller="attributecontroller">
<span data-ng-controller="attributevaluecontroller">
<select data-ng-model="detail.A" data-ng-change="getattributevalues(detail.A)" data-ng-options="Attribute.Attribute_Key as Attribute.Attribute_Desc for Attribute in Attributes"><option value="">--Select--</option></select><br />{{detail.A}}
<select data-ng-model="detail.V" data-ng-options="Attribute_Value.Attribute_Value_Key as Attribute_Value.Attribute_Value_Desc for Attribute_Value in AttributeValues"><option value="">--Select--</option></select>{{detail.V}}
</span>
<br />
<span data-ng-controller="saveattributecontroller">
<input type="button" value="submit" data-ng-click="attributesave(detail)"/>
</span>
</div>
</body>
</html>
//AttributeControler.cs
using System;
using System.Collections.Generic;
using MVC_APP1.Models;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_APP1.Controllers
{
public class AttributeController : Controller
{
//
// GET: /Attribute/
public ActionResult AttributeIndex()
{
Cafe_CPDEntities objEntity = new Cafe_CPDEntities();
var data = objEntity.Attributes.ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
public ActionResult getattributevalues(int id)
{
Cafe_CPDEntities objEntity = new Cafe_CPDEntities();
var data = objEntity.Attribute_Value.Where(m=>m.Attribute_Key==id);
//string test = data.FirstOrDefault().Attribute_Value_Desc;
return Json(data, JsonRequestBehavior.AllowGet);
}
public ActionResult attributesave(List<int> ReturnData)
{
return null;
}
}
}
// WebAPIAttributeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MVC_APP1.Controllers
{
public class WebAPIAttributeController : ApiController
{
public class GetAll
{
public string AttributeKey { get; set; }
public string AttributeValueKey { get; set; }
}
[HttpPost]
public string attributesave(HttpRequestMessage request,
[FromBody] GetAll getAll)
{
return "Data Reached";
}
}
}
Try to
$scope.attributesave = function (Data) {
var GetAll = new Object();
GetAll.AttributeKey = Data.AttributeKey;
GetAll.AttributeValueKey = Data.AttributeValueKey;
$http.post("WebAPIAttribute/attributesave", getAll)
.then(function(response){
//here your operations
})
}
(I THOUGHT I POSTED THIS EARLIER, BUT IT DID NOT SAVE)
I figured out the last part. I needed to add api/ to the route.
api/WebAPIAttributes/attributesave/
The call to webapi now goes through and passes the data from the screen.
Thanks so much to all those who helped answer the earlier issues I was having.
How do I enable Visual Studio to recognize and manipulate JSON data in the code-behind files? (In other words, resolve json does not exist in the current context error). I'd like to be able to:
Retrieve JSON data from AJAX calls forwarded from the client side
Interpret, change, or create JSON objects with C#
Send a valid JSON response back to the client side and read it with Javascript
Be able to do all of the above irrespective of the runtime environment (i.e. I can't always assure that I will have a third party package installed in Visual Studio)
I've seen many answers, but most suggest to either (1) install a json package or (2) play with using directives. I've tried many variations of the latter with no luck.
What is the proper way to include JSON support in Visual Studio?
How does one properly retrieve (e.g. from a POST AJAX call), manipulate (e.g. change), and send back (i.e. respond to the client) JSON data in C#? Very basic, primitive examples would help!
ASP.Net Web Form has WebMethod. You can call those static method from client-side using Ajax.
ASPX
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="DemoWebApplication.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<button type="button" onclick="postData();">Post Data</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
function postData() {
var user = { firstName: "John", lastName: "Doe" };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postjson") %>',
data: "{user:" + JSON.stringify(user) + "}",
contentType: "application/json",
success: function (msg) {
console.log(msg.d);
}
});
}
</script>
</form>
</body>
</html>
Code Behind
using System.Web.Script.Serialization;
namespace DemoWebApplication
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostJson(User user)
{
user.FirstName += "Test";
user.LastName += "Test";
return new JavaScriptSerializer().Serialize(user);
}
}
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
What is the proper way to include JSON support in Visual Studio?
Visual Studio is nothing to do with sending and receiving JSON. If you want a proper way, you might want to consider using ASP.Net Web API.
Not able to get SignalR working in my machine (with IE9). On entering some text and clicking submit, the text is not getting listed as intended. Also, I would expect the list getting updated from multiple instances of browser and It does not happen. There is no error. Could anybody help here?
C#
namespace TestSignalR.Hubs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for ChatHub.
/// </summary>
public class ChatHub : SignalR.Hubs.Hub
{
public void TestMessage(string message)
{
Clients.writeMessage(message);
}
}
}
ASPX
<input type="text" name="txtInput" id="txtInput" />
<button id="btnSubmit">Submit</button>
<ul id="messages">
</ul>
<script type="text/javascript" src="SignalR/Hubs"></script>
<script type="text/javascript">
$(document).ready(function (message) {
var chat = $.connection.chatHub;
chat.writeMessage = function (message) {
$("#messages").append("<li>" + message + "</li>");
};
$("#btnSubmit").click(function () {
var text = $("#txtInput").val();
chat.testMessage(text);
});
$.connection.hub.start();
});
</script>
Master page has the references for the JQuery and SignalR files:-
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.signalR-0.5.2.min.js" type="text/javascript"></script>
Today I was working with the same issue.
First you need to add an atribute to your Hub with the name, as following:
[HubName("chathub")]
public class ChatHub : SignalR.Hubs.Hub
The next to do is to change the order of your calls in the javascript. You need to do the connection next to instantiate the hub.
So, the code will be as following:
$(document).ready(function (message) {
var chat = $.connection.chatHub;
$.connection.hub.start();
chat.writeMessage = function (message) {
$("#messages").append("<li>" + message + "</li>");
};
$("#btnSubmit").click(function () {
var text = $("#txtInput").val();
chat.testMessage(text);
});
});
I hope it works for you.
Please install the 1.0 version of SignalR from Nuget as well. From your script references it looks like you are using 0.5.2 and the latest supported version at the time of writing this post is 1.0. Please download Microsoft.AspNet.SignalR from Nuget
I have a registration form(Default.aspx) which initially show's only 2 field's and a button (Name, email) when user click's on button Jquery makes an Ajax call to Default.aspx.cs function which query db to check for the user, and if it return no then the form expands itself adding registration fields.
I am not able to make a call to Defualt.aspx.cs
my Default.aspx code is :
<script type="text/javascript">
$(document).ready(function() {
$('#btnDownload').click(function() {
//$('#secondary').toggle(1000)
$.ajax({
type: "POST",
url: "Default.aspx/PassData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert('Failed');
}
});
</script>
And Default.aspx.cs is (for test purpose) :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private static string PassData(string id)
{
return "Pass";
}
}
But every-time I run the code JS returns error :
Uncaught ReferenceError: com is not defined
POST http://localhost:2305/temp/Default.aspx/PassData 500 (Internal Server Error)
I check few posts but non of them had been answered/resolved.
Any kind of help would be highly appreciated.
Thanks in advance
You need to decorate the method with [WebMethod] attribute.
EDIT
You'll need to add a ScriptManager and use some ASP.NET ajax framework methods. I think what you want to do is impossible with the out-of-the-box functionality.
One option will be to create a HttpHandler that will handle those methods. If the request is a POST, you can find the page type from the url (there's a method in the framework but I can't remember which one, you'll need to investigate), create a new instance and check if the method has the WebMethod (or another attribute you like). If it does, you can call it using reflection and render the result.
EDIT
As #Antony Highsky pointed out, it's possible. I think the solution is to add the [WebMethod] attribute and make de method public (it's private in the example).
Use **[WebMethod]
[WebMethod]
private static string PassData(string id)
{
return "Pass";
}
I am trying to post a request to the server but it wont hit when I use the debugger?
server:
public partial class _Default : System.Web.UI.Page
{
public string HitThis()
{
return "braza";
}
}
<script type="text/javascript">
var myRequest = new Request({
method: 'post',
url: '/Default.aspx/HitThis',
onSuccess: function () {
alert('good');
},
onFailure: function () {
alert('nope');
}
});
myRequest.send();
</script>
If you want to be able to call your HitThis method, you need to make that method, static, decorate it with the Web Method attribute and enable Page Methods on your ScriptManager
Example:
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
[WebMethod]
public static string HitThis()
{
return "Hello World";
}
You need to first understand how ASP.NET AJAX Script Services or PageMethod works! Page Methods has to be decorated with the WebMethod attribute and needs to be static.
[WebMethod]
public static string HitThis()
{
}
See this article that illustrates calling page method using jquery. You can adopt it with mootools. However, note that page methods needs content type to be JSON data and response will also be in JSON.
Perhaps you can write your own wiring logic in the ASP.NET page using Request.PathInfo if you want to use normal form posting. For example,
protected void Page_Load(object sender, EventArgs e)
{
if (this.Request.PathInfo == "HitThis")
{
HitThis();
}
}
In your method, you need to work with Response (HttpResponse) and after modifying the response, you need to end it (HttpResponse.End) so that normal page processing would not happen. If your method needs parameters then you have to pass them via form data and/or query string.