How to use jQuery dialog() instead of confirm() from within C# code? - javascript

I am a Frontenddeveloper without further knowledge of C#, so please excuse my maybe stupid question. I am currently trying to use jQuery UI Dialog to replace the common JavaScript alert() and confirm() boxes. This is working good so far in the Frontend but now I found this snippet in one of the C# pages and I don't know what's the best way to switch this from confirm() to jQuery dialog(). Any ideas?
string delCode = "javascript:"
+ "if ( confirm(\'Are you sure you wish to delete this?\')){ "
+ this.Page.ClientScript.GetPostBackEventReference(this, string.Empty)
+ ";} else { return false; }";
EDIT:
After playing around a bit more I found out, that it will not work without adding an OnClientClick Attribute to prevent the Postback when clicking the button. How do I add this Attribute from within the Code behind?
btnDelete.Attributes.Add("OnClientClick","foo");
does not work for me. What's the right way to solve this?
Here ist what I want to have, it's just simple JS so far (you see the C# snippet for the Button as a comment above the HTML content in the Fiddle):
https://jsfiddle.net/SchweizerSchoggi/xts01hrx/16/

Sadly, to push JavaScript from server to client inside of Web-Form's you'll need to utilize the current code you have to implement. Often, to avoid the excessive Postback issue, I would force server side controls, like the LinkButton to disable the form submission.
<asp:LinkButton id="lbExample" runat="server" OnClientClick="launch(); return false;" Text="Launch Dialog" />
<script type="text/javascript">
function launch() {
$('[data-rel="Example-Modal"]').dialog({
// Dialog logic.
}
}
</script>
This way it would work more like a traditional JavaScript in a web-page, or single page application. The official documentation based on the code above, which is correct extra functionality can be found here. As you denoted above, your only option to dynamically add:
ClientScript.RegisterOnSubmitStatement(this.GetType(), "ConfirmSubmit", jQuery);
You would simply create the button progmatically or find the button in the page, from code behind. I'll use the create, to show you what I mean:
public void Page_Load(...)
{
var lb = new LinkButton();
lb.OnClientClick = "launch();"
}

Related

How to make a live HTML preview textarea safe against HTML/Script Injection

I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.
However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:
</textarea>
<script>alert("Hello World!");</script>
<textarea style="display: none;">
And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).
I found this post; Live preview of textarea input with javascript html, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.
These few lines is what I use to live render HTML markup:
$(".main").on("keyup", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?
In order to sanitise your text area preview simply replace all the < and > with their html character code equivalents:
function showPreview()
{
var value = $('#writer').val().trim();
value = value.replace("<", "<");
value = value.replace(">", ">");
$('#preview').html(value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="writer" onInput="showPreview();">
</textarea>
<br/>
<hr/>
<div id="preview">
</div>
Edit: Actually, I think this solution is a little cleaner, and makes the below code unnecessary. In the velocity page all that is needed is to take advantage of the Spring framework. So I replace the textarea with this like so:
#springBindEscaped("myJavaObj.textAreaText" true)
<textarea id="actualTextArea" name="${status.expression}" class="myClass" rows="10" cols="120">$!status.value</textarea>
This paired with some backend Java validation and it ends up being a much cleaner solution.
But if you want a non-spring/ velocity solution, then this below works just fine
I cobbled together a quick fix as my main purpose is to eliminate the ability for others to execute scripts easily. It's not ideal, and I"m not claiming it to be the best answer, so if someone finds a better solution, please do share. I created a "sanitize" function like so:
function sanitize(text){
var sanitized = text.replace("<script>", "");
sanitized = sanitized.replace("</script>", "");
return sanitized;
}
Then the previous two event handlers now look like:
$(".main").on("keyup", "#actualTextArea", function () {
var textAreaMarkup = $('#actualTextArea').val();
var sanitizedMarkup = sanitize(textAreaMarkup );
$('#actualTextArea').val(sanitizedMarkup);
$('#previewTextArea').html(sanitizedMarkup);
});
// This one can remain unchanged and infact needs to be
// If it's the same as above it will wipe the text area
// on a highlight-backspace
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Along with Java side sanitation to prevent anything harmful being stored in the DB, this serves my purpose, but I'm very open to a better solution if it exists.

Validation before Submitting on prompt page

I am trying to use some sort of script on prompt page using HTML Item, what i am trying to accomplish is after clicking finish button script checked if there is nothing left black. Nothing means any of the prompt/filter (text, prompt, date/time) and if it is than it doesn't go through.
Hope i made things clear.
Thank You
Personally I think the fastest and easiest way if you don't already have a js framework is jQuery validate... check out this page, see the examples and give this a go. I should think the description you've provided will be covered in the basic usage examples for this plugin.
http://docs.jquery.com/Plugins/Validation
If you don't want to use jQuery as in Ben's answer, you can use the form's onSubmit event:
<form id="datform" action="http://path.to/action.script" onsubmit="return isValidated()">
...
...
'</form>
You'll then use a javascript function, ala
<script type="text/javascript">
function isValidated(){
var so=false;
return so;
}
</script>
Personally, I prefer jQuery but this allows for some on-the-fly validation

Confirm dialog box with anchor tag

My friend done this below coding for custom control
click
now i want to show confirm dialog box while click this anchor link.
Is it possible?. i want to write script as inline.
Do this :
click
But at some point, you'd want to stop using only inline code and have a look at other clearer ways to add javascript in your code.
You may use a script block like this in the HEAD of your HTML file :
<script>
function doOnClick(){
if (window.confirm('Really?')){
__doPostBack('id','msg');
};
}
</script>
And then your link becomes
click
Of course, this doesn't feel much simpler with only one function but it helps you put all your functions in the same place and make lighter and clearer html.
An alternative would be to use jQuery, so that you may totally avoid putting javascript in the html part.
The html is then
<a id=myLink>click</a>
And your script, now at the end of the body, is this one :
<script>
$(document).ready(function(){
$('#myLink').click(function(){
if (window.confirm('Really?')){
__doPostBack('id','msg');
};
});
// other codes will come here
});
</script>
You're not at all required to code it this way now, as you only have a very light function, but if your code grows I suggest you start considering it and look at the jquery tutorials.
Of course. Here is a small snippet, not elegant but it works...
click
I actually had to look this up because I haven't used confirm, alert and prompt in a very long time.
confirm returns true/false depening on what the user selected (OK/Cancel, respectively).
So your resulting code would be
click

User control with a client side API

Maybe I've picked a totally inappropriate/bad example.
What I have is a user control that contains a bunch of dynamically created Telerik RadGrids.
My user control is added to a couple of Telerik RadPageViews that are part of a RadMultiPage that is used alongside a RadTabStrip.
What I need to do is call a Javascript function in my usercontrol to update it's display whenever it's parent RadPageView is selected.
So basically I have the following Javascript code:
function OnClientTabSelected(sender, args)
{
// Get the MyControl that is on this tab
var myControl = $find("whatever");
// Call a method that updates the display
myControl.doSomething();
}
Thanks,
David
You can add a wrapper div in your User Control and then extend that div using jQuery to add your desired methods and properties. The trick is to set the div's id='<%=this.ID%>' - that way the div has the same ID as the User Control (which is fine because the User Control doesn't actually render anything - only its contents).
Then back on your containing page, you can just reference your UserControl's ID using $get('whatever') - and you'll actually select your extended div.. which will have all your methods and properties on it.
The nice thing about this approach is that all of your methods and properties and neatly scoped and nothing is in the global namespace.
I have a full demo solution and details here if you want more info:
http://programmerramblings.blogspot.com/2011/07/clientside-api-for-aspnet-user-controls.html
Just make a call to javascript method in input button if you are sure about the name of that function.
<input type="button" value="test" onclick="doSomething()" />
If you place any javascript code in the control that will be spit on the page and it will be available for calling provided both of them are in the same form.
for example your code will look like this if you look into the source of that page.
<script type="text/javascript">
function doSomething()
{
alert(new Date());
}
</script>
<div>
<span id="MyControl1_Label1">Dummy label</span>
</div>
<hr />
<input type="button" value="test" onclick="doSomething()" />
Edit: This is not a good way to access these methods in my opinion. When you are putting some javascript code inside a control then it should be used in that control only (There is no rule as such, its just a design suggestion). If you are trying to access javascript code of a control from outside that control then you need to revisit your design.
If you can give us more details on why you want to access that method, may be we can suggest some better way to do that.
Update: (As you have modified your question): Bit tricky to answer this as I dont have hands on experience with Rad controls. I guess there should be some feature which will help you to update the controls in that page without using javascript, may be have a look at clientside-API provided for Rad.
May be somebody who knows about RAD controls will help you.
You should make the control method public
public void doSomething
and call this from the page
myControl1.doSomething();

Can you mix ASP.Net and Unobtrusive JavaScript

Is it possible to mix the concept of Unobtrusive JavaScript with the event model of ASP.Net?
ASP.NET makes it very difficult, as every server side control requires a postback via the __doPostback javascript function.
You can make sure you are not using any server side controls, but this means you loose most of the benefits of ASP.NET.
Another option is to override the OnRender event and output different controls/javascript, but this is also quite a lot of work and defeats the purpose of ASP.NET.
You have much greater control when using ASP.NET-MVC.
yes, to a point. discounting standard controls and how they are built, there's not much stopping your from offloading all your own javascript to a separate file. the big hangup that comes to mind is referencing myControl.ClientID to render an element id in the middle of a script block. with a little planning, you can still minimize the amount of script you have to render in the page to work around this.
I realize that this question has already been answered but for anybody surfing in, I somewhat disagree with the accepted answer.
It depends on what controls you are using.
Not all the controls require JavaScript. The biggest culprit for me was always LinkButton. A regular button control does not use JavaScript at all however. On my pages, I actually use regular buttons and use CSS and JavaScript to make them into LinkButtons. The first step is to use CSS to make them look like links. If you really want to get fancy, you can detach the button, add an HTML anchor, and associate all the event handlers for the button with the anchor. This means that a user without JavaScript sees a regular button (HTML input) that is styled with CSS. Anybody using JavaScript will see an HTML link (
Also, if you use JQuery, it is very easy to select ASP.NET elements without worrying about all the extra mumbo-jumbo that ASP.NET adds to the IDs.
Example:
<asp:Button id='theButton' text='Click here' cssclass='linkbutton' runat='server' />
You can select this individual button using JQuery:
var theButton = $("input[name$='theButton']");
You can also replace everything of class 'linkbutton' with HTML anchors:
$(function() {
var buttons = $(".linkbutton");
buttons.each(function() {
var button = $(this);
var id = button.attr('id');
/*
* If a link button is not working
* it is likely because it does not
* have an ID attribute - check that
*/
if (id)
{
var text = button.attr('value');
var cssclass = button.attr('class');
button
.before("<a id='"+id+"' class='"+cssclass+"' href=''>"+text+"</a>")
.hide()
.detach();
$("a[id='"+id+"']").live('click', function(event) {
$(this).after(button);
button.click();
event.preventDefault();
});
}
});
});
Things like GridViews are a bit more work but also doable. I found that, after the initial honeymoon, I avoided those kinds of controls and just used repeaters anyway. Repeaters do not impose any nasty JavaScript either.
Anyway, it is certainly possible to do unobtrusive JavaScript with ASP.NET WebForms.

Categories

Resources