How to enable JSON support in Visual Studio (ASP.NET)? - asp.net

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.

Related

Get HTML from CURRENT aspx-Page to String Value (Codebehind)

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.

Why Can WebMethod Access Session State Without EnableSessionState?

I have a method on a page marked as a [WebMethod] that uses some session state as part of its operation. After I wrote this code, I suddenly had a flash of memory that you need to use EnableSessionState when you use session state in a [WebMethod] (e.g. see here: http://msdn.microsoft.com/en-us/library/byxd99hx.aspx). But it seems to be working fine. Why?
Sample code behind:
protected void Page_Load(object sender, EventArgs args) {
this.Session["variable"] = "hey there";
}
[System.Web.Services.WebMethod]
public static string GetSessionVariable() {
return (string)HttpContext.Current.Session["variable"];
}
Sample body html:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function getSession() {
$.ajax({
type: 'POST',
url: 'Default.aspx/GetSessionVariable',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
document.getElementById("showSessionVariable").innerHTML = msg.d;
}
});
return false;
}
</script>
<form id="form1" runat="server">
<div id="showSessionVariable"></div>
<button onclick='return getSession()'>Get Session Variable</button>
</form>
On http://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute.enablesession(v=vs.90).aspx, you will see that this applies to XML Web services (i.e., classes derived from System.Web.Services.WebService).
[WebMethod(EnableSession=true)]
Because your page presumably extends System.Web.UI.Page, it is not necessary to explicitly enable the session. On http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx, you can see that EnableSessionState is enabled by default for Pages (which you probably already know).
http://forums.asp.net/t/1630792.aspx/1
Answer of gsndotnet:
You are right but whatever you are saying is applicable to a method in context of WebServices. We also use same WebMethod attribute on the methods of a WebService (.asmx). So in context of Web Services when we want to allow the access to Session we have to add EnableSession = true. Whereas in context of PageMethods they already have access to Session as they are defined inside a class that inherits from Page class.
Your msdn link means that you use web service, i.e. class derived from System.Web.Services.WebService.
In your code you add your method directly on page, so it has access to session.

ajax request Mootools to asp.net webforms

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.

event not rendering by jquery to view in asp.net mvc

I am implementing the full calender in jquery in my asp.net mvc application by referring from here
but as per this blog it should be render the events on dates given in the controller action. but it is does not. i followed exact same steps . i checked many times there is no mistake. so why should be this happening? please guide me
Edited
Controller:
public ActionResult CalendarData()
{
IList<CalendarDTO> tasksList = new List<CalendarDTO>();
tasksList.Add(new CalendarDTO
{
id = 1,
title = "Google search",
start = ToUnixTimespan(DateTime.Now),
end = ToUnixTimespan(DateTime.Now.AddHours(4)),
url = "www.google.com"
});
tasksList.Add(new CalendarDTO
{
id = 1,
title = "Bing search",
start = ToUnixTimespan(DateTime.Now.AddDays(1)),
end = ToUnixTimespan(DateTime.Now.AddDays(1).AddHours(4)),
url = "www.bing.com"
});
return Json(tasksList);
}
private long ToUnixTimespan(DateTime date)
{
TimeSpan tspan = date.ToUniversalTime().Subtract(
new DateTime(1970, 1, 1, 0, 0, 0));
return (long)Math.Truncate(tspan.TotalSeconds);
}
Added Class
public class CalendarDTO
{
public int id { get; set; }
public string title { get; set; }
public long start { get; set; }
public long end { get; set; }
public string url { get; set; }
}
Site.Master
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />
<link href="../../Content/fullcalendar.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/fullcalendar.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript"></script>
View Page I used Index page which given as default
$(document).ready(function() {
$('#calendar').fullCalendar({
events: "/Home/CalendarData"
});
});
And added div with id "calender".
-----------------------------------------------------------------------------------------
Edited Quetion 2
As you can see above my method returning the Json out put. but I am getting error as:
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
So I just add the parameter as JsonRequestBehavior.AllowGet to Json() . but it is asking for download the json output file. rather than this it must be redirect to view as usual , right ? why should this is happening?
Probably a stupid question but did you include jquery-1.3.2.js and fullcalendar.js in your site? Remember that with the default ASP.NET MVC 2.0 project template, only jquery-1.4.1.js is included in the Scripts folder. Also I would recommend you downloading the latest versions of jquery and the fullCalendar plugin.
Also here's another gotcha when returning JSON in the CalendarData action:
return Json(tasksList, JsonRequestBehavior.AllowGet);
Contrary to ASP.NET MVC 1.0, in ASP.NET MVC 2.0 the JsonRequestBehavior.AllowGet is necessary if you want this action to be accessible over GET which is what I think the calendar plugin is doing.
Of course you would have seen this error if you used FireBug to analyze the AJAX request/response data.

Returning a string from a http GET using asp.net web forms project

I am trying to dynamically generate JavaScript with just a URL get request.
I have accomplished this with asp.net MVC by just returning a string from the action and writing the script tag like this.
<script type='text/javascript' src='script/get/123'></script>
The problem is I need to accomplish the same type of dynamically generated script from a asp.net web forms project.
How would I return dynamiccally generated string with a GET request to a page (or web service) in a asp.net Web Forms project?
You could write a generic handler:
public class CustomJsHandler : System.Web.IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/javascript";
context.Response.Write("alert('Hello world');");
}
public bool IsReusable
{
get
{
return true;
}
}
}
and then specify the address of this handler:
<script type="text/javascript" src="/customjshandler.ashx"></script>

Resources