How to pass arguments in alert message - aspx page alert - asp.net

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.

Related

Database notification using signalr and asp.net not displaying the data in UI

i followed the tutorial to from one of the online blog and am able get the application out with out error, but main issue is its not giving error as well as output.
My hub class looks like this
public void NotifyAllClients(string msg)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationsHub>();
context.Clients.All.displayNotification(msg);
}
My ASPX.CS page looks like this
protected void Page_Load(object sender, EventArgs e)
{
SendNotifications();
}
public void SendNotifications()
{
string message = string.Empty;
string conStr = ConfigurationManager.ConnectionStrings["TestDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(conStr))
{
string query = "SELECT [Message] FROM [dbo].[MessageBuffer]";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
message = reader[0].ToString();
}
}
}
NotificationsHub nHub = new NotificationsHub();
nHub.NotifyAllClients(message);
}
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
if (e.Type == SqlNotificationType.Change)
{
SendNotifications();
}
}
and My aspx page is --
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script src="Scripts/jquery.signalR-2.1.2.js"></script>
<script src="signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var notify = $.connection.notificationsHub;
notify.client.displayNotification = function (msg) {
$('#newData').append('<li><strong>' + msg + '</li>');
};
$.connection.hub.start();
});
</script>
<div style="padding:10px 0px 10px 10px">
New Messages:
<ul id="newData"></ul>
</div>
</body>
</html>
i have done different samples, i have used same format to display, i am able to get those out in a hand, but here i am stuck with this. i am getting value in aspx.cs page, it calling the DB, which i have given in global.asax. and i have added sqldependency as well, enbabled broker in DB. but issue is still there. i cant see anything in UI.
Thanks in advance
I had a similar problem a while back. I just used the hub method name attribute and it worked for me. So you want something like
[HubMethodName("SendNotifications")]
public string SendNotifications()
And then at the front end just do
$.connection.hub.start(function () {
notify.server.SendNotifications();
});
Update
You could have a span the way I have in my code. so something like
<div>
<ul>
<li>New Messages:<span id="newData">0</span></a></li>
</ul>
</div>
Then do
$('#newData').text(msg);

Value returned from jQuery is always null when accessing it from codebehind in asp.net

My master page contains a menu which is dynamically created in <ul><li><li><ul/> format.
When I click on it, I want to pass its ID to codebehind for passing it into base class for its permission. But am getting value from jQuery always null in codebehind - but am getting value in jQuery function.
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').click(function () {
debugger;
var vals = $(this).text();
document.getElementById('hdnForLabel').value = vals ;
});
});
</script>
This page load am using in Master Page.
protected void Page_Load(object sender, EventArgs e)
{
GetMenus();
string pageids = hdnForLabel.Value;
BasePage BasePage = new BasePage();
BasePage.LoadSettings(pageids );
}
Have you checked if the ID of your rendered hidden control is really 'hdnForLabel'? It might be something along the line of 'ctl00_hdnForLabel'.
You could use jQuery to check if the value has been set on the client side:
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').click(function () {
debugger;
var vals = $(this).text();
document.getElementById('hdnForLabel').value = vals ;
alert( "Value: " + $("#hdnForLabel").val());
});
});
</script>
Please note that a value set for hdnForLabel.Value is only available when the page is sent back to the server via postback
protected void Page_Load(object sender, EventArgs e)
{
GetMenus();
if (IsPostBack) {
string pageids = hdnForLabel.Value;
BasePage BasePage = new BasePage();
BasePage.LoadSettings(pageids );
}
}

Binding data to html5 DataList in 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>

Prevent double submiting in asp:CommandField

Have this code:
<asp:UpdatePanel ID="id">
<asp:CommandField ButtonType="Image" InsertImageUrl="url/here" ShowInsertImage="true" ValidationGroup="valGr" />
</asp:UpdatePanel>
How to prevent double clicking on this button in C# code.
You can first create a flag that hold the submit and add it to the form. Then open and close that flag when the UpdatePanel go for update and while is waiting for the return.
For example this code is allow the submit of the form (and of the UpdatePanel) only when the
fAlloToSubmit is true:
<script>
var fAlloToSubmit = true;
function AllowFormToRun()
{
if(!fAlloToSubmit)
alert("Please wait for the page to fully re-loaded.");
return fAlloToSubmit;
}
</script>
and on code behind you set that on the form.
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes["onsubmit"] = "return AllowFormToRun();";
}
And now for the UpdatePanel, you open that flag the moment you go for update, eg the moment you click that command as:
<script>
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
function InitializeRequest(sender, args) {
// here is run when you click the command on the UpdatePanel
fAlloToSubmit = false;
}
function EndRequest(sender, args) {
// here is come after the upadate of the command
fAlloToSubmit = true;
}
</script>
The trick here is that I hold the form to submit and not looking every control on page to disable it.

Validation Before Postback Event on Masterpage Asp.net

I was wondering if anyone knew of a way to do some client side validation with jquery and then run the postback event manually for a asp.net control?
Here's a sample Master page
i.e.
<script type="text/javascript">
$(document).ready(function() {
$("#<%=lnkbtnSave.ClientID %>").click(function() {
alert("hello");
// Do some validation
// If validation Passes then post back to lnkbtnSave_Click Server side Event
});
});
</script>
<asp:LinkButton ID="lnkbtnSave" runat="server" onclick="lnkbtnSave_Click" ><asp:Image ID="Image3" runat="server" ImageUrl="~/images/save.gif" AlternateText="Save" />Save</asp:LinkButton>
Master Page Code Behind
public delegate void MasterPageMenuClickHandler(object sender, System.EventArgs e);
public event MasterPageMenuClickHandler MenuButton;
protected void lnkbtnSave_Click(object sender, EventArgs e)
{
// Assign value to public property
_currentButton = "Save";
// Fire event to existing delegates
OnMenuButton(e);
}
protected virtual void OnMenuButton(EventArgs e)
{
if (MenuButton != null)
{
//Invokes the delegates.
MenuButton(this, e);
}
}
Content Page Code behind
protected void Page_Load(object sender, EventArgs e)
{
Master.MenuButton += new Form.MasterPageMenuClickHandler(Master_MenuButton);
}
void Master_MenuButton(object sender, EventArgs e)
{
switch (Master.CurrentButton)
{
case "Save":
Save();
break;
case "New":
Response.Redirect("ContentPage.aspx");
break;
default:
break;
}
}
Also the control lnkbtnSave is in a master page so how would i determine which content page i'm on since each content page will have it's own controls to validate.
Thanks for any help
If you look at it in reverse it could be simplified. Instead of doing validation and then initiating the postback, you could validate and prevent the postback if needed.
$('#<%= lnkbtnSave.ClientID %>').click(function(e) {
if (!validate()) {
e.preventDefault(); //will stop the page from posting back.
}
});
If you really need to initiate the postback (and do it the other way) you could explicitly call the __doPostBack() function that ASP.NET puts on the page for you after doing your validation.
// This does the exact same thing as above, but it explicitly calls __doPostBack
// If you use the above code __doPostBack will be called automatically for you.
$('#<%= lnkbtnSave.ClientID %>').click(function(e) {
if (validate()) {
__doPostBack('<%= lnkbtnSave.ClientID %>','');
}
e.preventDefault();
});
Let me know if any of this needs clarification.
For the first question you should be able to just return true to cause the linkbutton to postback and return false to stop it.
$(document).ready(function() {
$("#<%=lnkbtnSave.ClientID %>").click(function() {
alert("hello");
var isValid = false;
// Do some validation
return isValid;
});
});
For your second question, you could have each page add their own version of the validation script, and have the function in the masterpage use it to determine validity:
Master Page:
$(document).ready(function() {
$("#<%=lnkbtnSave.ClientID %>").click(function() {
return pageIsValid();
});
});
Content Page:
function pageIsValid() {
var isValid = false;
//validation logic
return isValid;
}
You can just use a CustomValidator control and set it's ClientValidationFunction property.

Resources