I am actually buidling a web application and I need to get data of the local environment of the machine viewing the application.To do this, I use a little javascript script such as:
<script language="javascript">
function GetUserName()
{
//Permits to get username of client machine
var wshell = new ActiveXObject("WScript.Shell");
var arpege = wshell.ExpandEnvironmentStrings("%USERNAME%");
document.getElementById("arpege").value=arpege;
}
</script>
<input type=hidden id="arpege" runat=server />
My problem is that this script is executed after the page is loaded and so I can't use it on the page load...
My code on the page load is:
protected void Page_Load(object sender, EventArgs e)
{
myConnection.ConnectionString = ActionSource.ConnectionString;
myConnection.Open();
String account = arpege.value;
...
}
But i just get "" in account...
Thanks for your help,
Quentin
Page_Load occurs on the server side before any data is being sent to the client.
you can't do that without initiating a new postback once the page is loaded.
Solution coming up...
EDIT:
So, it (might) be possible to achieve this using some jQuery
$(document).ready(function() {
var wshell = new ActiveXObject("WScript.Shell");
var arpege = wshell.ExpandEnvironmentStrings("%USERNAME%");
__doPostBack('__Page', arpege);
});
And catch it on the server side:
public void Page_Load(object sender, EventArgs e)
{
string arpege= Request["__EVENTARGUMENT"];
}
Worth's a shot!
A variant of the proposition made by Shai could be the following:
generate an asyncpostback on a hidden button.
Like that, the logic could be separated from the Page_Load, and
put instead in the handler attached to the input which generated the asyncpostback.
I don't like to put too much logic in the page_load event, i find it confusing.
the implementation will be a little more complicated though
Get the username server side in Page_Load instead of with an ActiveX control.
protected void Page_Load(object sender, EventArgs e)
{
myConnection.ConnectionString = ActionSource.ConnectionString;
myConnection.Open();
String account = User.Identity.Name;
// ...
}
Also, ActiveX only works in Internet Explorer - User.Identity.Name works on the server and therefor all browsers.
The ASPX code:
<body>
<form id="form1" runat="server">
<input type="hidden" id="hdnUser" runat="server" />
<input type="hidden" id="hdnRun" runat="server" value="true" />
<asp:Label ID="lblSayHello" runat="server" Text="I dont know you"></asp:Label>
</form>
<script type="text/javascript">
$(function () {
var run = $('#hdnRun').val();
if (run == 'true') {
var wshell = new ActiveXObject("WScript.Shell");
$('#hdnUser').val(wshell.ExpandEnvironmentStrings("%USERNAME%"));
$('#form1').submit();
}
});
</script>
</body>
The Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(hdnUser.Value))
{
hdnRun.Value = "false";
lblSayHello.Text = String.Format(#"Hello, {0}", hdnUser.Value);
}
}
The best (easiest) way that I know of sending data from the client to the server is to
1. Store it in an asp hidden field
2. Click an ASP button via javascript
3. Handle the data in the OnClick Event
For example:
ASPX Page
<asp:HiddenField ID="myHf" class="myHf" runat="server" />
<asp:Button ID="myButton" class="myButton" runat="server" OnClick="myButton_Click" style="display: none;" />
Javascript
function SendMyData(data) {
document.getElementByClassName('myHf').value = data;
document.getElementByClassName('myButton').click();
//I use classes since those won't change - IDs become really long and messed up
//in the actual page, and may change depending on where the element is placed.
}
CodeBehind
protected void myButton_Click(object sender, EventArgs e)
{
//Do whatever you want with myHf.Value
MyServerMethod(myHf.Value);
}
I think that doing it this way is better than using the Page_Load and submitting the form, just because if you are doing enough of these, the Page_Load method can get huge. But that's just my opinion.
Related
I have 2 hrefs like below in asp.net 4.5:
</i>
</i>
where I have some process to do in page_load in c# like
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//loading data from db;
}
}
When I click on this a href, the page_load event is triggered and IsPostBack comes as false. Therefore, it is loading the data again and again whenever someone clicks previous or next page hrefs, causing a performance issue. I need to prevent this happening, meaning that I want IsPostBack = true after an href link is clicked. What is the best way to handle this issue?
I have tried to use onclientlick="return false;", it did not work.
I have tried to use asp:button and asp:linkbutton like below, did not work.
<asp:Button ID="btnPrev" runat="server" Text="left" OnClick="RedirectPreviousPage" />
protected void RedirectPreviousPage(object sender, EventArgs e)
{
var prevPage = CurrentPage == 1 ? -1 : CurrentPage - 1;
Response.Redirect("/Admin/" + prevPage);
}
What is the best solution? Any help or advise would be appreciated. I've checked lots of previous topics with related issue, but couldn't find a proper solution for my case. Apologies if I am causing a duplication. Regards.
Edit: also did not work.
<script>
function RedirectPreviousPage()
{
window.location.href = "/Admin/<%= prevPage %>";
}
</script>
</i>
Changing hrefs into "asp:LinkButton" and setting AutoPostBack property to true for those linkbuttons fixed my issue.
I have a menu in my web application like this
<div>
<ul>
<li><a href="http://localhost:52451/Voronezh/Settings.aspx">Settings</a</li>
<li><a href="http://localhost:52451/LoginPages/Welcome.aspx">Log out</a</li>
</ul>
</div>
I would like to set these href links dynamically if some special condition is true.
I've tried the following:
HTML code
<li><a runat="server" id="toSettings" onserverclick="toSettings_ServerClick">Settings</a></li>
C# code
protected void toSettings_ServerClick(object sender, EventArgs e)
{
if (condition)
toSettings.HRef = "http://localhost:52451/Voronezh/Settings.aspx";
else
{...}
}
but it doesn't work: I stay on the same page instead of moving to the Settings page.
Where is a mistake? What should be changed?
Thanks in advance.
Changing the HRef won't do much here - it changes the link, it doesn't have any direct effect on the page. Try Response.Redirect, I think this is what you're looking for. I.e:
// inside the if statement
Response.Redirect("Settings.aspx"); // note - this is the local path
Assuming this is ASP.NET C#
Redirect method from the HttpResponse should be what you are looking for.
Reference:
https://msdn.microsoft.com/en-us/library/a8wa7sdt(v=vs.110).aspx
If you want to build your menu dynamically in code behind you should probably use a <asp:Literal ID="menu" runat="server"/> tag in ASPX and fill it in the Page_Load event like
if (!Page.IsPostBack) {
menu.Text = GenerateMenu();
}
private string GenerateMenu() {
if (yourcondition) {
return "<div><ul><li></li></ul></div>";
} else {
}
}
Another alternative to doing a postback, executing the logic, and then doing a redirect would be to change the link tag to the hyperlink control, execute the logic on page load, and set the properties dynamically.
HTML:
<asp:HyperLink id="toSettings" Text="Settings" runat="server"/>
Code Behind
protected void Page_Load(object sender, EventArgs e) {
toSettings.NavigateUrl = "http://localhost:52451/Voronezh/Settings.aspx";
}
This way you could even change the text (use toSettings.Text = "Text to display";) or the visibility (use toSettings.Visible = false;) if needed.
I read data from database in sreverside (for example a name) and I want to use this name in clientside. But I don't pass the name to clientside(in javascript method). How can I achieve this?
(using asp.net)
using HiddenField:
serverside:
protected void callbackPanel_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
{
hiddenFieldGenel.Add("license", "license1");
}
clientside:
<dx:ASPxHiddenField ID="hiddenFieldGenel" runat="server" ClientInstanceName="hiddenFieldGenel">
</dx:ASPxHiddenField>
function saveClick(s, e) {
var licence = hiddenFieldGenel.Get('license');
}
If its just a single value, you can use Hidden variable:-
<asp:HiddenField ID="NameHidden" runat="server" ClientIDMode="Static" />
And you can simply access it using Javascript or jQuery:-
$('#NameHidden').val();
document.getElementById('NameHidden');
i have one textbox and one button both on a gridview , when user clicks on button i want to get the textbox text and save to database then clear the text! i used code below it works fine and saves to database but cant clear the textbox why ?
protected void sendcm_Click(object sender, EventArgs e)
{
try
{
Button sendcm = (Button)sender;
GridViewRow gvrow = (GridViewRow)sendcm.NamingContainer;
int ActivityTypeID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["ActivityTypeID"].ToString());
int SourceID = Convert.ToInt32(activity.DataKeys[gvrow.RowIndex].Values["SourceID"].ToString());
TextBox tt = (TextBox)activity.Rows[gvrow.RowIndex].FindControl("cmtextbox");
if (tt.Text != "")
{
BusinessLayer.StatusComment_Table ncm = new BusinessLayer.StatusComment_Table();
ncm.Id = Convert.ToInt32(Session["ID"].ToString());
ncm.Statusid = SourceID;
ncm.Statuscommentdate = System.DateTime.Now;
ncm.Statuscommenttext = tt.Text;
ncm.Save();
tt.Text = ""; // its not working !!!!
}
}
protected void Page_Load(object sender, EventArgs e)
{
SessionLable.Text = Session["ID"].ToString();
if (!IsPostBack)
{
getData();
}
}
public void getData()
{
activity.DataSource = BusinessLayer.Activity_Table.GetByProfileData(ID, -1, activity.PageSize);
activity.DataBind();
}
You need to do this at the UI level.
Use jquery.post to call the method that saves the data.
return something back to the $.post callback to tell jquery that the post s complete,
then do something like $('#mytextfield').val('')
assuming that the text box has an ID. I am assuming this is HTML?
you might need to rebind your grid because from the code that you posted it's not clear that where are you re binding your grid.
You need to enable AjaxPostback in your page. After that, in your Page_Load logic, include the code
if(IsPostBack){...}else{...}
So you can handle the construction of UI elements depending on whether this is a fresh new view of the page or a postback (page refreshed due to user clicking the button). UI elements are sent to the browser, after that, there is no way for the server to change it except to refresh the page itself.
The manual (and the one I recommend) way is to do this via jQuery postback. As pointed out in the other answer, you'll need to setup an endpoint for the client browser to connect. After the server has done its job, return the result to the client. Then use jQuery to update the textbox.
i did this to solve my problem !
<asp:TextBox ID="cmtextbox" type="text" clientid="cmtextbox" TextMode="MultiLine" placeholder="نظر دهید..." Rows="1" style="resize:none" class="form-control" runat="server"></asp:TextBox>
<asp:Button ID="sendcm" style="margin-top:2px;" OnClick="sendcm_Click" class="btn btn-success btn-sm pull-left " OnClientClick="ClearTextbox(this)" runat="server" Text="ارسال" />
</script>
<script type="text/javascript">
ClearTextbox = function (that) {
$(that).prevUntil('div.stop', '[ClientID="cmtextbox"]').val('');
}
</script>
In reference to the question of mine at deleting record when it shouldn't
How can I access asp.net button's "Text" in a code behind method?
Here's how button looks like:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:Button ID="HiddenButton" Text="" runat="server" OnClick="Deleting_Click" />
This is my code behind:
protected void Deleting_Click(object sender, EventArgs e)
{
I have already tried:
HiddenButton.Text = Request.Form["HiddenButton"].ToString();
and
Request["__EVENTARGUMENT"];
But nothing has worked, can someone show me the right direction please?
Edit
Can I use this any way? but not sure:
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
});
Update
What actually happening is, when user clicks on delete linkbutton in GridView this, happens,
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton link = e.Row.Cells[4].Controls[2] as LinkButton;
if(link.Text == "Delete")
link.OnClientClick = "return ConfirmationBox("+ ((DataRowView)e.Row.DataItem)["userID"].ToString() +")";
}
}
Now in JS I am catching the action Displaying a messagebox and always returning false, however I am setting text of hidden button so that I can send it to method in code behind for deleting a record using UserID
function ConfirmationBox(userID)
{
var elem = document.getElementById('<%= HiddenButton.ClientID %>');
elem.value = userID;
$.blockUI({ message: $('#question'), css: { width: '275px' }
});
return false;
}
Now I got the ID I needed and can make user choose yes or no, if user clicks yes then this happens,
$('#yes').click(function() {
$.unblockUI();
// $('<%= HiddenButton.ClientID %>').trigger('click');
__doPostBack('<%=HiddenButton.ClientID %>', "");
});
You can cast the sender to a button and get the information from that.
protected void Deleting_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
var text = btn.Text;
}
Update
When choosing (Cast)object vs object as object see Direct casting vs 'as' operator?
Update 2
When you want to pass some arguments through to your code which are set via JavaScript, you can pass them through with the EVENTARGUMENT
So when calling __doPostBack('',''); You can set it here. In your case you need to update your code to be;
__doPostBack('<%=HiddenButton.ClientID %>', 'Your Argument Here');
Then within your Deleting_Click method, you can get the argument;
string parameter = Request["__EVENTARGUMENT"];