Binding data to html5 DataList in asp.net - asp.net

I'm trying my hands with HTML5. Is it possible to bind data to datalist in html5 as we bind data from a datatable to asp.net dropdown control.
Where i can find this details. any pointers is much appreciated. :)
Thanks

1) Assign runat="server" to the datalist so that it can be accessed from code behind:
Enter your favorite browser name:<br />
<input id="browserName" list="browsers" />
<datalist id="browsers" runat="server" />
2) Loop through the DataTable, construct and concatenate a list of options using a StringBuilder and add the result to the InnerHtml property of the datalist
protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("BrowserName");
table.Rows.Add("IE");
table.Rows.Add("Chrome");
table.Rows.Add("Firefox");
table.Rows.Add("Opera");
table.Rows.Add("Safari");
var builder = new System.Text.StringBuilder();
for (int i = 0; i < table.Rows.Count; i++)
builder.Append(String.Format("<option value='{0}'>",table.Rows[i][0]));
browsers.InnerHtml = builder.ToString();
}
If you're going to need this functionality in multiple places in your site, you can either create a WCF service and call it via jQuery where you can populate the datalist or create an HTTP handler like this:
1)Add a Generic Handler to your project and call it AutoCompleteHandler.ashx
2)Inside AutoCompleteHandler.ashx put:
public class AutoCompleteHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Clear();
var options = new System.Text.StringBuilder();
options.Append("<option value='IE'>");
options.Append("<option value='Chrome'>");
options.Append("<option value='Firefox'>");
options.Append("<option value='Safari'>");
options.Append("<option value='Opera'>");
context.Response.Write(options.ToString());
context.Response.End();
}
public bool IsReusable
{
get{return false;}
}
}
3)Call the handler via jQuery when the page loads and populate the datalist with the returned result:
<script src="Scripts/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.post('AutoCompleteHandler.ashx', function (data) {
$('#browsers').html(data);
});
});
</script>

Related

How to pass arguments in alert message - aspx page alert

I would like to pass arguments in an alert message.
var bankCodeName = "ABC";
alert("<%= Common.GetResourceText("BankCodeSearch_SearchByBranchAlert") %>", bankCodeName);
Default.aspx.cs
public partial class _Default: Page
{
private string clients;
public string Clients { get { return clients; } }
protected void Page_Load(object sender, EventArgs e)
{
clients = "test msg";
}
}
Default.aspx
you need to put your javascript code inside Script
<script type="text/javascript">
//your code
</script>
tag so the Aspx renderer can understand the difference between HTML and Javascript code.
<script type="text/javascript">
var bankCodeName = "ABC";
var client='<%= Clients %>';
alert(bankCodeName+client);
</script>
var client='<%= Clients %>'; line saves your code behind variable value to JavaScript variable.

Downloading large files asp.net mvc 3?

I have a large pdf file (upto 2 GBs) on a database server which I want to send to client for download. Also, I have size limitations on my web server and cannot store complete file on it, after requesting from data server. I am using asp.net mvc 3. Any suggestions on how can I accomplish this? Also I want it to be asynchronous since I don't want to block the user from clicking other buttons on the web page.
I have tried using this code.
//code for getting data from data server into inputstream
HttpContext.Response.ContentType = "application/pdf";
HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
HttpContext.Response.BufferOutput = false;
try
{
using (Stream inputStream = resp.GetResponseStream())
{
byte[] buffer = new byte[SegmentSize];
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, SegmentSize)) > 0)
{
HttpContext.Response.OutputStream.Write(buffer, 0, bytesRead);
HttpContext.Response.Flush();
}
}
}
catch (Exception ex)
{
//some code
}
This downloads the file but then I don't know how to make it asynchronous? Also is there any other way to do the download that would be asynchronous too?
You can use AJAX which is Asynchronous. For that use a library like JqueryUI and a plugin, take a look a this example
http://www.plupload.com/example_custom.php
Im sure this will do! :D
Turns out in my final application I did not use web service but simple AJAX and ASPX pages this is how I got it done!
Default.ASPX file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CloudWF._Default"
Culture="auto" meta:resourcekey="PageResource1" UICulture="auto" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link type="text/css" href="css/redmond/jquery-ui-1.8.21.custom.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="jsEng" runat="server">
<Scripts>
<asp:ScriptReference Path="~/js/jquery-1.7.2.min.js" />
<asp:ScriptReference Path="~/js/jquery-ui-1.8.21.custom.min.js" />
</Scripts>
</asp:ScriptManager>
<input type='submit' value='Process New Records' id='trigger' onclick='BeginProcess(); return false;' />
</div>
</form>
</body>
<script type="text/javascript">
var btnStart;
$(function () {
btnStart = $("#trigger").button();
imgLoad = $("#loader").hide();
});
function BeginProcess() {
btnStart.val("Collecting Data...");
//to get the value of the radiobuttons
//alert($('input[name=A]:checked').val()) --> [name=*] where *= whatever the name of the radioset
// Create an iframe.
var iframe = document.createElement("iframe");
// Point the iframe to the location of
// the long running process.
iframe.src = "process.aspx";
// Make the iframe invisible.
iframe.style.display = "none";
// Add the iframe to the DOM. The process
// will begin execution at this point.
document.body.appendChild(iframe);
btnStart.val("Processing...");
imgLoad.show();
btnStart.button("disable");
}
function UpdateProgress(RecordComplete, Message, step) {
btnStart.val("Downloaded Record " + RecordComplete + Message);
$("#progressbar").progressbar({
value: step
});
if (step >= 100) {
imgLoad.hide();
btnStart.val("Download Complete!");
}
}
</script>
Process.aspx.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
public partial class process : System.Web.UI.Page
{
WebClient wc = new WebClient();
Dictionary<string, string> AudioURLs = new Dictionary<string, string>();
protected void Page_Load(object sender, EventArgs e)
{
// Padding to circumvent IE's buffer*
Response.Write(new string('*', 256));
Response.Flush();
ProcessRecords();
}
public void ProcessRecords()
{
int recTotal;
recordList = (IQueryable<Record>)(Session["UNPROCESSED"]);
recTotal = recordList.Count();
if (recordList.Count() > 0)
{
foreach (Record record in recordList)
{
try
{
curRow++;
step = ((decimal)curRow / (decimal)recTotal) * 100;
CreateDictionary();
CreateFolderwithAudios(record.tSessionID);
//record.processed = true;
db.SubmitChanges();
UpdateProgress(curRow, " of " + recTotal, step);
}
catch (Exception x)
{
HttpContext.Current.Response.Write("Exception: " + x.Message);
}
}
Session["UNPROCESSED"] = null;
}
}
public Dictionary<string, string> CreateDictionary()
{
AudioURLs.Clear();
#region Add Values to Dictionary
return AudioURLs;
}
public void DownloadAudios(string _subFolder, Dictionary<string, string> _AudioSources)
{
foreach (KeyValuePair<string, string> kvp in _AudioSources)
{
if (kvp.Value.StartsWith("http://"))
{
try
{
wc.DownloadFile(kvp.Value, audiosPath + "\\" + _subFolder + "\\" + kvp.Key + ".wav");
}
catch (WebException webex)
{
throw new WebException(webex.Message);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
}
public void CreateFolderwithAudios(string folderName)
{
try
{
//create the folder where the audios are going to be saved
Directory.CreateDirectory(audiosPath + folderName);
//create and read the Dictionary that contains the URLs for the audio files
DownloadAudios(folderName, AudioURLs);
}
catch (AccessViolationException ae)
{
HttpContext.Current.Response.Write(ae.Message);
}
catch (System.Exception x)
{
HttpContext.Current.Response.Write(x.Message);
}
}
protected void UpdateProgress(int PercentComplete, string Message, decimal step)
{
// Write out the parent script callback.
Response.Write(String.Format(
"<script>parent.UpdateProgress({0}, '{1}',{2});</script>",
PercentComplete, Message, step));
// To be sure the response isn't buffered on the server.
Response.Flush();
}

Render Macro control on page load in umbraco template

I am trying to load the razor script which exists as a separate macro in umbraco. I am using umbraco 4.7.0
I am basically doing geo-targeting and hence need to run the script each time on a page load. so I am looking for something like :
<script type="c#" runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Call the Macro here
}
Obviously I can do this in the template
<umbraco:Macro Alias="GeoTargetting" runat="server" />
but I need to call this macro before any control is loaded in the page.
PLease help.
Thanks
This appears to work alright:
Template:
<umbraco:Macro Alias="Sandbox" runat="server"></umbraco:Macro>
<asp:Label runat="server" ID="Label1" Text="Yo"></asp:Label>
Macro Script:
#using System.Web.UI.WebControls
#using umbraco.MacroEngines
#inherits DynamicNodeContext
#{
Page page = HttpContext.Current.Handler as Page;
page.Load += new EventHandler(page_Load);
}
#functions
{
static void page_Load(object sender, EventArgs e)
{
Page page = sender as Page;
Label label = FindControlRecursive(page, "Label1") as Label;
label.Text = "Hello";
}
private static Control FindControlRecursive(Control Root, string Id)
{
if (Root.ID == Id)
return Root;
foreach (Control Ctl in Root.Controls)
{
Control FoundCtl = FindControlRecursive(Ctl, Id);
if (FoundCtl != null)
return FoundCtl;
}
return null;
}
}
Note: The FindControlRecursive() method is from this forum thread.

How do i maintain the state of my Html Controls on postback with JQuery and JSON?

I have a form with a collection of Html and ASP Server Controls. Im using JSON to preload some drop-down lists.
I want to maintain the states of these drop-down lists on postback. Im quite new to JSON, can anyone help?
If you can use HTML select element instead. Thus, you can get the selected value of select element on the server and register an hidden field to maintain the value. While you are loading the items so you can check the registered hidden field to retrieve the previous selected value.
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script type="text/javascript">
var sv = document.getElementById("SelectedValue");
var v = (sv != null && sv.value != "" ? sv.value : null);
var o = document.getElementById("DropDownList1");
for (var i = 0; i < 10; i++) {
var item = document.createElement("option");
item.innerHTML = "item" + i;
item.setAttribute("value", "item" + i);
if (("item" + i) == v)
item.setAttribute("selected", "selected");
o.appendChild(item);
}
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
firstly, you should create an HTTPHandler to generate the JSON and get it using getJSON method from jQuery. Lastly, you have to get the selected value on the Load event of the page and maintain the value to a HiddenField for the next time. The following code demonstares it.
public class JsonGenerator : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
JavaScriptSerializer ser = new JavaScriptSerializer();
context.Response.Write(ser.Serialize(new object[]
{
new { Text = "Item1", Value = 1 },
new { Text = "Item2", Value = 2 } ,
new { Text = "Item3", Value = 3 }
}));
}
public bool IsReusable
{
get
{
return false;
}
}
}
<select id="DropDownList1" name="DropDownList1" />
<asp:Button ID="Button1" runat="server" Text="Button" />
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("JsonGenerator.ashx",
null,
function(r) {
var ddl = $("#DropDownList1"), hf = $("#SelectedValue");
$.each(r, function(k, v) {
ddl.append("<option value='" + v.Value + "'>" + v.Text + "</option>");
});
if (hf.length > 0)
ddl.children("[value='" + hf.val() + "']").attr("selected", "selected");
});
});
</script>
protected void Page_Load(object sender, EventArgs e)
{
string selectedValue = Request["DropDownList1"];
if (!string.IsNullOrEmpty(selectedValue))
Page.ClientScript.RegisterHiddenField("SelectedValue", selectedValue);
}
Don't let the browser do the post, do it yourself with jQuery. On the callback replace a results div with the returned html.
Assuming you've marked your form with class="ajaxform" and your results div with id="results" then something like this (not fully tested)...
// Submit form.ajaxform
// Get the returned html, and get the contents of #results and
// put it into this page into #results
var submit = function() {
$.ajax({
type: "POST",
data: $("form.ajaxform").serialize(),
success: function(data, textStatus) {
$("#results").replaceWith($("#results", $(data)));
}
});
};
$("form.ajaxform input[type=submit]").click(submit);
// I think you'll need this as well to make sure the form doesn't submit via the browser
$("form.ajaxform").submit(function () { return false; });

User Control with Input Parameter

I have a user control with property (*.acsx.cs):
public partial class controls_PersonAccessStatus : System.Web.UI.UserControl
{
public Person Person { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
}
Is there some way to pass parameter to this control in *.aspx, something like this
<% foreach (Person p in persons) { %>
<uc:PersonAccessStatus ID="PersonAccessStatus" runat="server" Person=p />
<% } %>
Yes. You can create a property on the UserControl. I typically use it to enable or disable functions of a control. It is simple to assign a value in the aspx.
<uc:PersonAccessStatus ID="PersonAccessStatus" runat="server" EnableSomething="true" />
I am not sure about the syntax for your example as I usually keep code out of the aspx, so I would do the looping in the code.
foreach (Person p in persons)
{
control = LoadControl("~/App_Controls/PersonAccessStatus.ascx")
as PersonAccessStatus;
control.Person = p;
SomeContainer.Controls.Add(control);
}
Thank you g. You really helped me although I have not found more elegant solution. From *.aspx side it looks so:
<%foreach (Person p in persons)
{
controls_PersonAccessStatus control = LoadControl("~/App_Controls/PersonAccessStatus.ascx") as controls_PersonAccessStatus;
control.Person = p; %>
<%=RenderControl(control) %>
<%}%>
Where RenderControl ia a helper function:
public string RenderControl(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
return sb.ToString();
}
All of the parameter and functions must be declared with <%= this.ID %> in the asp user control to use it more than one time.
For example:
var ii<%= this.ID %> = 0;
or
function load_2v<%= this.ID %> ()
{
var BI1 = document.getElementById("<%= Li1.ClientID %>");
var BI2 = document.getElementById("<%= Li2.ClientID %>");
switch (ii<%= this.ID %>) {

Resources