How can I retain client side html controls on postback? I have tried setting enableviewstate="true" but that did not work. A workaround I've done was to build a server side function that takes all the posted values and resets them via ClientScript.RegisterStartupScript and call this on every postback method. Is there an easier and more time efficient way of doing this?
You have have html control to keep their values on postback by making them runat="server" e.g.
<input type="text" id="txt1" runat="server" />
You need to create the controls at every postback. If you're looking for something a little easier to implement, take a look at the DynamicControlsPlaceholder control. It's a nifty little control that takes away most of the pain associated with persisting dynamic content.
Can you use HiddenField?
Now on clicking any button at client side, Preserve the data in HiddenField.
Use JQuery document.ready function to set the value again from HiddenField again. JQuery docuemnt.ready will be called on each Postback.
Related
I have a div tag that has a click event and the method I'm trying to call is from the codebehind.
This is my div tag
<div class="DivA" runat="server" id="ThisDiv" onclick="<%ClickMe();%>"></div>
The method is a simple
public void ClickMe()
{
Response.Redirect("www.google.ca");
}
I'm just testing this before I add the real stuff to it. The error that it is throwing is...
JavaScript critical error at line 16, column 49 in http://localhost:24307/DIVPAGE.aspx
SCRIPT1002: Syntax error
this is the line that it is giving me
<div id="ThisDiv" class="DivA" onclick="<%ClickMe();%>"></div>
I have tried changing the
<%ClickMe();%>
to
<%=ClickMe()%>
But that throws the same error. Another thing I don't understand is when you look at the line with the error that it is missing the runat tag and has added other characters to the onclick event.
Thanks
You have a concept problem here, do this, and test it will work:
<asp:LinkButton id="lbClickMe" runat="server" OnClick="ClickMe">
<div class="DivA" id="ThisDiv">
The Click Me Button!
</div>
</asp:LinkButton>
That's it, when runat=server is specified ASP.NET page parser will process the element as server side, so for this elements/controls no server tags in markup are allowed except data binding tags inside control templates. So to call you method you have to put a runat server on a control that haves the Click event, this is the case of the LinkButton, inside of him you can put your div for some specific styling of your UI.
Also not that, if you really want to have the your div behaving like that, there is no problem in complicating what is simple, but in that case please do this instead:
<asp:LinkButton id="lbClickMe" runat="server" OnClick="ClickMe" Visible="False"></asp:LinkButton>
<div class="DivA" id="ThisDiv" onclick="<%= Page.GetPostBackEventReference(lbClickMe) %>"></div>
The GetPostBackEventReference extracts the javascript code necessary to simulate your link button click, but once more is preferable to use directly the link button if you can.
Hope it helps,
Regards.
The <%= %> syntax emits a string, it doesn't do anything, like a redirect.
You need to do your redirect client-side with this javascript:
window.location = 'http://my.url.com';
If you need to interact with server side code, you need to do so with AJAX communicating to a web service to get the URL you need, and then performing the redirect described above.
Update
Sorry lads, brain freeze.
Yes, indeed, you can inject a string that will be evaluated as a click handler, but the handler must be a javascript function, not a server-side one! Once the page is rendered, it can no longer interact with the server save for communicating with a web service (or if we want to get technical, web sockets as well).
You can't call server-side C# methods from the DOM like that. You can only call JavaScript functions in an HTMLElement's onclick handler.
It is correct that you can call server-side methods using the template language, however this will be executed at the time of rendering the page; you could, for example, render the results of that server-side method, but you can't use a server-side method as a handler for a client-side event. The onclick event on a DOM element can only call a JavaScript function.
ASP web controls also have an OnClick event attribute, which is probably what's confusing you; this is different from the onclick event attribute on DOM elements (ASP will create additional code for its web controls, e.g. in case of an asp:button). This works using ViewState and a postback to the server. The onclick event for a DOM element however won't do those things for you.
Adding runat="server" will convert your element to an ASP control, however it will only be an HtmlControl. In the case of a <div>, it will be an HtmlGenericControl which simply writes out the onclick attribute of your element as it is.
Is it possible to add drop down items throught javascript, and then get it on server side?
I have
<asp:DropDownList ID="testDropDown" CssClass="listClass" runat="server"/>
<asp:Button ID="saveButton" runat="server" Text="Добавить" OnClick="saveButtonClick" />
After page load javascript add items to drop down
$('.listClass').append("<option value='value1'>Text1</option>");
But after saveButton click i have empty drop down on server
Any dynamic changes that happen on the client-side will not be automatically replicated on the server side.
You need to record the fact the action took place somehow (using, for instance an <asp:HiddenField> control)... then on the post-back, check for whether the action happened and replicate the value that took place on the client.
Also, be careful, as ASP.NET will probably throw an exception due to the fact that control is returning a value that ASP.NET did not populate the control with in the first place. To counteract this, either set the EnableEventValidation="false" in your <#Page> declaration, or add all possible values using Page.ClientScript.RegisterForEventValidation
You cannot do this in ASP.NET because the values are contructed using the ViewState on the server side.
Check this. It may be helpful for you: Options added to <select> by javascript lost in postback
iv'e got an asp button which performs another task besides postback
i have done this by adding javascript code to the button as follows
if( !IsPostBack )
btn1.Attributes.Add("onclick", "f();");
i'm not sure of 2 things
the first :
where in the cs code i should add the function f() , currently i'm doing it in page load
while ignoring postbacks because then the function would have already been added(i might be wrong)
the second :
is there any to make the function execute only if the page was validated ? (after postback)
thanks in advance
eran.
I would use OnClientClick instead of adding the click event throug the attributes. As for your JavaScript, I would add it in the ASPX part. Depending on what the function does, you might be able to avoid the code behind all together and do something like this:
<asp:Button ID="Button1" runat="server" Text="Hi" OnClientClick="javascript:return f();" OnClick="Button1_Click" />
From your f() function, kick off the validation, and return true if validation passes, otherwise return false. If OnClientClick returns true the page will post back, and if it returns false the page will not post back.
1st Question
You will need to add it each time.
btn1.Attributes.Add("onclick", "f();");
2nd Question
You can check the validity of a page by checking the Page.IsValid Property
Unobtrusive JavaScript
If you're serious about javascript then you don't want to write inline javascript.
You will want to create an event handler in javascript code inside the script tags or in a external file.
If you're using .NET 4 server control id:s will be good, else I would use jquery's
contains selector. Search for the given server control ID.
in my application i have the playvideo page where video will play, below that i have the option for sharing the video like adding to favorite ,playlist and sending mail.
when i click on any of the link the page is postbacking and video will start from the first.
i place update panel for link button even though it is not working (video is playing from the first i.e., page is postbacking. can u help me. thank you
Actually, the part of page that is within the UpdatePanel does the postback. Make sure you have only those controls(for instance, your links) inside the UpdatePanel.
Alternatively, you can use multiple UpdatePanels; for instance one for your video and one for the links. In this case note that, when one UpdatePanel gets updated other UpdatePanels also gets updated, which you may not want; so all you have to do then is to mark the UpdateMode property to Conditional and call YourDesiredUpdatePanel.Update() method manually - whenever required.
Btw, updating selected portions of the page also reduces the load on the server
Or you may want to look into using client callbacks instead of a postback. But since client callback uses XMLHTTP, which means Microsoft implementation of AJAX, therefore callbacks are just awesome as long as your are working with IE.
You might want to try taking advantage of Page Methods to do the work you need done server side.
http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Also, if you want to prevent a control from posting back, you can add return false to the end of your javascript onclick event on the control.
For example, if you had an asp button you were using you could do this:
<asp:Button ID="myButton" runat="server" OnClientClick="DoThingsInJavascript(); return false;" />
Or if you were just using a standard button you could say:
<input type="button" onclick="DoThingsInJavascript(); return false;" />
I've never really liked the update panel and I have sometimes found it's behaviour awful. Have you thought of trying something like a proper ajax call from Javascript
Is there a way to call a javascript function when the selectedIndex of a select input has been changed?
Using this code in the c# code behind file
riskSeverityDropDown.SelectedValue = Convert.ToString(planRisk.Severity);
riskSeverityDropDown.SelectedIndexChanged += new EventHandler(riskSeverityDropDown_SelectedIndexChanged);
riskSeverityDropDown.AutoPostBack = true;
want to change something else on the page with javascript when the index is changed.
Any help would be much appreciated.
Thanks in advance
You're already going to server code (AutoPostBack is true), which means you're going to rebuild the entire page anyway. Running javascript at this point would be a little silly, because any changes you make to the DOM will be lost and any ajax requests you want to send can instead be handled by normal server code. If you really want to do this, you can just register the script to run when the page loads after the postback.
On the other hand, if you can do this without any server code at all then set AutoPostBack to false and the basic html select control has a nice onchange event you can handle.
Simply add an onchange to your asp:dropdownlist.
<asp:DropDownList ID="riskSeverityDropdown"
AutoPostBack="True"
SelectedIndexChanged="riskSeverityDropDown_SelectedIndexChanged"
onChange="functionName()"
runat="server" />
or to do this from codebehind use:
riskSeverityDropdown.Attributes["onchange"] = "functionName()";
You want to add an attribute to that drop down called "onchange" and set it to call a JavaScript method of your choosing.
Use JQuery. It exposes a rich set of events that you can use to code against practically anything in a uniform manner. It is also quite easy to learn, compact, and popular.
In short you can't go wrong if you use JQuery. It is meant to solve problems like this well.