Allow for "<<" to be submitted, without disabling "validaterequest" - c#

I'm wondering if anyone knows of a way to allow something like "<<" to be submitted, without setting validaterequest=false
I have a creole parser, and the recommended plugin/macro syntax is:
<<macro-name argo0=foo arg1=bar argN=qux>>

I wrote a little ‘encodeMyHtml’ JavaScript function that is called on the OnClick event when the HTML form’s submit button is clicked. The function encodes the user’s HTML input for the field I’ve specified into a harmless string before it is passed to the server. When I receive that input on the server I simply decode and go on my way.
ValidateRequest is happy, our users are happy, our peers are happy, heck we’re happy.
I add my ‘encodeMyHtml’ JavaScript function in my user control’s OnPageLoad method. This way I can make sure that my JavaScript is added to the parent page only once, no matter how many controls are on the page.
In my control’s OnPageLoad I call this:
private void addEditorJavaScript()
{
// create our HTML encoder javascript function
// this way it shows up once per page that the control is on
string scr = #"<script type='text/javascript'>function encodeMyHtml(name){
var content = document.getElementById(name).value
content = content.replace(/</g,'<');
content = content.replace(/>/g,'>');
document.getElementById(name).value = content;
}</script>";
// add the javascript into the Page
ClientScriptManager cm = Page.ClientScript;
cm.RegisterClientScriptBlock(this.GetType(), "GlobalJavascript", scr);
}
In my control’s ASPX I’m using a gridview. I wrap the gridview’s update asp:LinkButton in a span tag, and in that span tag I put my OnClickEvent.
<span onclick="encodeMyHtml('<%# UniqueID.Replace("$", "_") %>_FormViewContentManager_ContentTextBox')">
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True" CommandName="Update" Text="[Publish]" />
</span><span onclick="encodeMyHtml('
When I get the input on the server side I simply call a couple of Replace methods on the input string to decode the HTML, and I’m done.

You could do a javascript regex replace for "<\S" on the specific field on form submit. But it would fail for browsers that don't support javascript.

You can encode the "<<" on the client using Javascript:
<script language="javascript">
function encodeString(str) {
return str.replace(/</gi, '<').replace(/>/gi, '>');
}
</script>
And then on the server use Server.HtmlDecode to return the string to its original form.

Related

Hide URL when mouse hover over asp:HyperLink

I have seen javascript:void(0) method used on <a> tags in HTML to hide the target URL of the hyperlinked object. Now I want to do the same on a <asp:HyperLink>, what should I do?
I am doing ASP.NET and here's the markup:
<asp:HyperLink runat="server" ID="hl1">Blah blah blah</asp:HyperLink>
In the codebehind I specified the NavigateUrl for hl1 using HttpUtility.UrlDecode method.
I tried hl1.Attributes[href]="javascript:void(0)"; in coebehind, does not work. Cannot open the NavigateUrl anymore.
You need to store the url you are wanting to navigate to in a hidden field and just set NavigateUrl = "#" in the markup as shown below. This way when user's cursor hovers over the link, the actual navigate URL will never be displayed at bottom of browser.
Then attach a click event handler on client-side for the hyperlink which you do by just setting onclick attribute of the hyperlink to a JavaScript function called navigate. The actual redirection to a new page is done by this navigate function.
In this situation, you will only see the URL of current page suffixed with #. For example, if your current page URL is http://localhost/mysite/view.aspx then it will show http://localhost/mysite/view.aspx# at bottom of browser.
Markup needed
<asp:HyperLink runat="server" ID="hl" NavigateUrl="#"
onclick="navigate();">Some Text</asp:HyperLink>
<asp:HiddenField ID="hdnURL" runat="server" Value="http://www.microsoft.com" />
JavaScript needed
<script type="text/javascript">
function navigate() {
window.location.href = document.getElementById("<%=hdnURL.ClientID%>").value;
}
</script>
Another approach that you can use if you must set the NavigateURL for the hyperlink in code-behind is as below. In this approach, you need to remove the NavigateURL before the content renders and store it in a global variable called linkUrl. The event that fires before the content renders is pageLoad and we will use that event to do this hack.
Global variable in JavaScript must always be declared outside all methods.
Then on clicking the hyperlink, we can obtain the value from the global variable of linkUrl and redirect user to that location.
Note: Keep the markup of the hyperlink the same as in first approach. But remove the hidden field from that markup.
<script type="text/javascript">
function navigate(event) {
window.location.href = linkURL;
}
var linkUrl = null;
function pageLoad() {
var link = document.getElementById("<%=hl.ClientID%>");
linkURL = link.getAttribute("href");
link.setAttribute("href","#");
}
</script>

Calling codebehind method from markup and is throwing javascript error

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.

pass parameter to one function in the code behind in C# from javascript

I am trying to pass parameter to one function in the code behind in C# from javascript
<script type="text/javascript">
$(document).ready(function () {
$("#some_id").click(function () {
var id = document.getElementById('HiddenField2');
var a = <%=btn_Click(id)%>;
});
});
</script>
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "item_id")%>' />
code behind
public string btn_Click(String item_id)
{
/*do some thing*/
return null;
}
But this piece of code always giving me error of context. That id is not defined in this context.
Can some please let me know what wrong i am doing?
First, var id is javascript and the code within <%= %> is C#. You can't pass a variable between the languages like that.
Second, the value of id in this case is going to be a DOM element which C# can't use anyways. If you want to get the value of HiddenField2 within the code behind you can use HiddenField2.Value.
Third, since you're using ASP.net, instead of using jQuery's .click handler you should use the onServerClick attribute to wire up the button click behavior to btn_Click.
The button click event in C# will be triggered by Postback when your browser post data back to asp.net
I do not understand why you use HiddenField here,so my suggestion do not consider about it
Solution 1:
first you can extract your code in btn_Click to a HttpHandler(*.ashx in asp.net),then use Ajax by using js framework like jQuery to send data to your HttpHandler,data returned by HttpHandler can be processed by js
sample code is here
Solution 2:
if your code in btn_Click is relevent to your page, just use ajax Get method, the data will send to your page,the data returned by your data will be processed by js too
In the end, if you are new to web, I recommend you to learn or implement asp.net MVC, in my opinion, it is more flexible than asp.net webform

How to call javascript method in asp.net web application

I want to use a javascript function inside a c# function
protected void button1_Click(object sender,EventArgs e){
//javascript function call ex.
/*
boolean b=the return of:
<script type="text/javascript">
function update() {
var result = confirm("Do you want to delimit the record?")
if (result) {return true;}
else {
return false;
}
}
</script>
*/
}
how can i do such a thing? i want when user press yes return true and i know he pressed yes...can i do so?
If you're trying to add JavaScript to your page from asp.net, you can use the ClientScript class.
string script = "function update() { var result = confirm(\"Do you want to delimit the record?\") if (result) {return true; } else { return false; } }";
ClientScript.RegisterClientScriptBlock(this.GetType(), "someKey", script, false);
If you're trying to call (client side) JavaScript functions from your asp.net code behind, then absolutely not. When the page posts and your C# is run, any JavaScript that was on the page no longer exists.
You're mixing two different technologies. C# runs on the server. It renders an HTML page (which may include Javascript). This page is then sent to a client's browser, where Javascript finally gets executed.
In Javascript you can prompt user about record deletion or whatever, and then you have to either navigate to another page or use AJAX to send result to the server.
I suggest that you get a good ASP.NET book. It will clear many uncertainties for you.
If you're putting this message on an <asp:Button> with postback just add the confirm dialog to the OnClientClick attribute like so:
<asp:Button ID="Button1" runat="server"
OnClientClick="return confirm('Do you want to delimit the record?');" />
If you're simply trying to create the functionality of letting the server know that a button was clicked, you're over complicating things. If you really need to dynamically insert Javascript then what Adam mentioned is worth looking into. But I highly doubt that this is the correct approach for what you're trying to do.
You should really only dynamically insert Javascript when you're worried about performance AND you have a lot of content to send.
If dynamically inserting Javascript (ie. lazy loading) is not your main concern, then here is a very simple example of what most folks would usually do to achieve the functionality you're aiming for.

Submit Page with just Code Behind Using C#

I am creating a callback page that receives info from a payment gateway and then updates a database. I then want it to 'submit' itself automatically to a 'thank you' page, passing the order number as a hidden field.
I have looked at httpwebrequest, but I can't see with this solution how it will 'post itself' if that's the right way to put it.
Any help on ho to achieve this would be greatly appreciated.
If the callback page is regular ASP.NET you could do a server-side Response.Redirect or Server.Execute.
If not you can do a client-side post in javascript:
<form action="yourThankYouUrl.aspx">
<input type="hidden" name="callbackValue" value="yourCallbackValue" />
</form>
<script type="text/javascript">
document.forms[0].submit();
</script>
So, why not using that receive page to also show what you need and save the trouble to have one more page?
If you still want to have a 2nd page just to show the result, at the end of the processing you can write:
Session["job-id"] = "12345679";
Response.Redirect("my2ndpage.aspx");
in that 2nd Page, you simply assign the session text to the control you will have
HiddenField1.Value = Session["job-id"].ToString();

Categories

Resources