asp.net return data in Page_Load - asp.net

If a query string param exists in my page request I want to query the database on the server in the Page_Load and then return the result to the client. I can do the query string param check and query the DB but how do I return the data to the page and on the javascript side how do I access that data?
Ideally I would return JSON of an object structure and it would be returning an array of them.

Yes, returning JSON would be the best option. I'm not sure how you query your database (Do you use LINQ or ADO.NET DataTables, etc)
If you don't have custom object of type you want to send, I recommend you create one. Then you should get an array of them.
Example:
public class Person {
string Name { get; set; }
int Age { get; set; }
}
Person[] pArr = new Person[5];
Then you can use a third party library like this to create an string representaion of that array in JSON.
string json = JsonConvert.SerializeObject(product);
Then you write that json string to the Response object so its sent down to the client, by overriding the Render method of the page.
// Don't expect this code to work as it is, but take this as a guidance
Response.Clear();
Response.Write(json);
Response.Close();
on the client side use jQuery library send a request to page, and process the JSON response for you.
$.getJSON('url', function(data) {
//process data
});
Here is my suggestion if you don't want to use an AJAX request for this:
Use the objects as you would normally do in the page_load, and convert it to a JSON string as explained above.
Then use ClientScriptManager to create an JavaScript variable on the client side when it loaded.
ClientScript.RegisterClientScriptBlock(typeof(Page), "unique_key", "var myObjectList = " + json, true);
After this when the page loads you will have an variable named "myObjectList" with the list of objects without having to make a different AJAX call.
You can directly refer that variable in your javascript and do necessary processing.
Hope this helps.

Related

How to send templated emails?

How does one send a templated Postmark message on ASP.NET? I'd imagine it would be done in this way:
TemplatedPostmarkMessage message = new TemplatedPostmarkMessage
{
From = "demo#demo.com",
To = "someone#else.com",
TemplateId = 1738,
TemplateModel = some_passed_in_model
};
The question now arises, what exactly is TemplateModel? From the API on Postmark's site, it seems like a JSON object, but in the definition from the DLL, it's as follows:
public object TemplateModel { get; set; }
I tried creating my own object with variable names that correspond to those on the Postmark template, however that does not work (it just sends a blank template). Postmark also does not have any documentation on how to use TemplatedPostmarkMessage in ASP.NET yet.
We send a dictionary of <string, object>, I believe you can use more complex models but a dictionary will get the job done.

How do QueryString parameters get bound to Action method parameters?

I have a webforms project, and am attempting to run some code that allows me to make a call to an MVC route and then render the result within the body of the web forms page.
There are a couple of HttpResponse/Request/Context wrappers which I use to execute a call to an MVC route, e.g.:
private static string RenderInternal(string path)
{
var responseWriter = new StringWriter();
var mvcResponse = new MvcPlayerHttpResponseWrapper(responseWriter, PageRenderer.CurrentPageId);
var mvcRequest = new MvcPlayerHttpRequestWrapper(Request, path);
var mvcContext = new MvcPlayerHttpContextWrapper(Context, mvcResponse, mvcRequest);
lock (HttpContext.Current)
{
new MvcHttpHandlerWrapper().PublicProcessRequest(mvcContext);
}
...
The code works fine for executing simple MVC routes, for e.g. "/Home/Index". But I can't specify any query string parameters (e.g. "/Home/Index?foo=bar") as they simply get ignored. I have tried to set the QueryString directly within the RequestWrapper instance, like so:
public class MvcPlayerHttpRequestWrapper : HttpRequestWrapper
{
private readonly string _path;
private readonly NameValueCollection query = new NameValueCollection();
public MvcPlayerHttpRequestWrapper(HttpRequest httpRequest, string path)
: base(httpRequest)
{
var parts = path.Split('?');
if (parts.Length > 1)
{
query = ExtractQueryString(parts[1]);
}
_path = parts[0];
}
public override string Path
{
get
{
return _path;
}
}
public override NameValueCollection QueryString
{
get
{
return query;
}
}
...
When debugging I can see the correct values are in the "request.QueryString", but the values never get bound to the method parameter.
Does anyone know how QueryString values are used and bound from an http request to an MVC controller action?
It seems like the handling of the QueryString value is more complex than I anticipated. I have a limited knowledge of the internals of the MVC Request pipeline.
I have been trying to research the internals myself and will continue to do so. If I find anything I will update this post appropriately.
I have also created a very simple web forms project containing only the code needed to produce this problem and have shared it via dropbox: https://www.dropbox.com/s/vi6erzw24813zq1/StackMvcGetQuestion.zip
The project simply contains one Default.aspx page, a Controller, and the MvcWrapper class used to render out the result of an MVC path. If you look at the Default.aspx.cs you will see a route path containing a querystring parameter is passed in, but it never binds against the parameter on the action.
As a quick reference, here are some extracts from that web project.
The controller:
public class HomeController : Controller
{
public ActionResult Index(string foo)
{
return Content(string.Format("<p>foo = {0}</p>", foo));
}
}
The Default.aspx page:
protected void Page_Load(object sender, EventArgs e)
{
string path = "/Home/Index?foo=baz";
divMvcOutput.InnerHtml = MvcWrapper.MvcPlayerFunctions.Render(path);
}
I have been struggling with this for quite a while now, so would appreciate any advice in any form. :)
MVC framework will try to fill the values of the parameters of the action method from the query string (and other available data such as posted form fields, etc.), that part you got right. The part you missed is that it does so by matching the name of the parameter with the value names passed in. So if you have a method MyMethod in Controller MyController with the signature:
public ActionResult MyMethod(string Path)
{
//Some code goes here
}
The query string (or one of the other sources of variables) must contain a variable named "Path" for the framework to be able to detect it. The query string should be /MyController/MyMethod?Path=Baz
Ok. This was a long debugging session :) and this will be a long response, so bear with me :)
First how MVC works. When you call an action method with input parameters, the framework will call a class called "DefaultModelBinder" that will try and provide a value for each basic type (int, long, etc.) and instance of complex types (objects). This model binder will depend on something called the ValueProvider collection to look for variable names in query string, submitted forms, etc. One of the ValueProviders that interests us the most is the QueryStringValueProvider. As you can guess, it gets the variables defined in the query string. Deep inside the framework, this class calls HttpContext.Current to retrieve the values of the query string instead of relying on the ones being passed to it. In your setup this is causing it to see the original request with localhost:xxxx/Default.aspx as the underlying request causing it to see an empty query string. In fact inside the Action method (Bar in your case) you can get the value this.QueryString["variable"] and it will have the right value.
I modified the Player.cs file to use a web client to make a call to an MVC application running in a separate copy of VS and it worked perfectly. So I suggest you run your mvc application separately and call into it and it should work fine.

Convert Results of LINQ to SQL Query to XML/JSON

I wish to populate a JavaScript array with the results of a database query. From what I understand, a good approach is to populate a bunch of directories on my server with serialized XML or JSON files which my JS functions can then read into without having to access the database. Is this true? Should the database write these XML files upon user interaction, or should they be prepopulated?
From the details you have provided:
I Personally would create a Web Service endpoint returning your linq query serialized to JSON using JSON.NET or an equivalent. The endpoint can then be called using ajax within your client page.
You can check this example out on ASP.NET for how to create a asmx (legacy) web service. Also you can look at this example of using the [WebMethod] attribute .
A web method in your code behind files.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetMyQueryResultsAsJson()
{
var results = GetQueryResults();
var jss = new JavaScriptSerializer();
string json = jss.Serialize(results);
return json;
}
A ajax call on your client page:
function loadData() {
var myArray = [];
$.getJSON("<%= ResolveUrl("~/MyPage.aspx/GetMyQueryResultsAsJson") %>", function (data) {
$.each(data, function(obj) {
myArray.push([obj.id, obj.someValue, obj.AnotherValue]);
});
});
}
I used jQuery ajax with generic http handler returing json
I created handler and put my business logic there.
It return me the result in form of json
I iterated the json using jquery.
And created my html form that.
Edit 1
Here are some useful links
http://www.codeproject.com/Articles/203621/Call-HTTPhandler-from-jQuery-Pass-data-and-retriev
http://www.sharepointnutsandbolts.com/2010/11/sp2010-ajax-part-4-returning-json-from.html
Edit 2
You can also take benefit of jtemplate
http://www.joe-stevens.com/2010/01/05/using-the-jtemplate-jquery-plugin-with-ajax-and-asp-net/
http://encosia.com/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/

Best Practices when using .NET Session for temporary storage?

I'm still relatively new to .NET and ASP.NET MVC, and I have had a few occasions where it would be nice to store information retrieved from the DB temporarily so it can be used on a subsequent server request from the client. I have begun using the .NET Session to store this information, keyed off of a timestamp, and then retrieve the information using the timestamp when I hit the server again.
So a basic use case:
User clicks 'Query' button to gather information from the system.
In JS, generate a timestamp of the current time, and pass this to the server with request
On server, gather information from DB
On server, use unique timestamp from client as a key into the Session to store the response object.
Return response object to client
User clicks 'Generate Report' button (will format query results into Excel doc)
Pass same timestamp from #2 down to server again, and use to gather query results from #4.
Generate report w/o additional DB hit.
This is the scheme that I have begun to use in any case where I use the Session as temporary storage. But generating a timestamp in JS isn't necessarily secure, and the whole things feels a little... unstructured. Is there an existing design pattern I can use for this, or a more streamlined/secure approach? Any help would be appreciated.
Thanks.
You may take a look at TempData which stores the data in Session.When you pull something out of TempData it will be removed after the Action is done executing.
So, if you put something in TempData in an Action, it will live in TempData across all other actions until its requested TempDatafrom TempData again.
You can also call TempData.Peek("key") which will keep it in memory until you call TempData["key"] or TempData.Remove("key")
Ok, I'm not sure I understand you correctly as the JS timestamp step seems superfluous.
But this is what I would do.
public static string SessionReportKey = "Reports";
public static string ReportIDString = "ReportID";
public Dictionary<string, object> SessionReportData
{
get
{
return Session[SessionReportKey] == null ?
new Dictionary<string, object>() :
(Dictionary<string, object>) Session[SessionReportKey];
}
set
{
Session[SessionReportKey] = value;
}
}
public ActionResult PreviewReport()
{
//retrive your data
object reportData = GetData();
//get identifier
string myGUID = new GUID().ToString();
//might only need [SessionReportData.Add(myGUID, reportData);] here
SessionReportData = SessionReportData.Add(myGUID, reportData);
//in your view make a hyperlink to PrintReport action with a
//query string of [?ReportID=<guidvalue>]
ViewBag[ReportIDString] = myGUID;
return View(reportData);
}
public FileContentResult PrintReport()
{
if(SessionReportData[QueryString[ReportIDString]] == null)
{
//error no report in session
return null;
}
return GenerateFileFromData(SessionReportData[QueryString[ReportIDString]]);
}

Windows Azure access POST data

Ok, so I can't seem to find decent Windows Azure examples. I have a simple hello world application that's based on this tutorial. I want to have custom output instead of JSON or XML. So I created my interface like:
[ServiceContract]
public interface IService
{
[OperationContract]
[WebInvoke(UriTemplate = "session/create", Method = "POST")]
string createSession();
}
public class MyService : IService
{
public string createSession()
{
// get access to POST data here: user, pass
string sessionid = Session.Create(user, pass);
return "sessionid=" + sessionid;
}
}
For the life of me, I can't seem to figure out how to access the POST data. Please help. Thanks!
If you have an HttpContext there may be a Request object that would have the form data. I'm basing part of this off the ASP.Net tag on this question, so if that is incorrect then there may be the need to handle this another way but it looks a lot like a web service to my mind.
EDIT: HttpRequest is the class that has the Form property that should be where the POST data is stored if this is an HTTP request. This is part of System.Web so it should be ready to be used pretty easily, as I recall.
Sample code showing the Request.Form property:
int loop1;
NameValueCollection coll;
//Load Form variables into NameValueCollection variable.
coll=Request.Form;
// Get names of all forms into a string array.
String[] arr1 = coll.AllKeys;
for (loop1 = 0; loop1 < arr1.Length; loop1++)
{
Response.Write("Form: " + arr1[loop1] + "<br>");
}
This presumed there was an HttpRequest instance around.
WCF Simplified Part 4: Comparing the Request/Reply and One-Way Patterns passes in a parameter so that your "createSession" method would have to take in those strings it would appear. I'm used to the ASP.Net world where there are some built-in objects like Request, Response, Server, Application and Session.
Yes, if you did try changing the method signature as there are ways to pass in parameters in that last example I linked though I don't know if that would work in your case or not.

Resources