using a string format with parameters to set onclick - c#

Why doesn't this work?
<input type="button" id="btnAccept" value="Accept" onclick='<%# String.Format("accept('{0}','{1}','{2}','{3}-{4}');", Container.DataItem("PositionID"), Container.DataItem("ApplicantID"), Container.DataItem("FullName"), Container.DataItem("DepartmentName"), Container.DataItem("PositionTitle"))%>' />
The onclick doesn't do anything.

Your best bet is to look at the generated HTML. I think it's a really good habit to check the generated HTML in text format and how it renders on-screen, all the time. Besides errors such as this (which can easily be spotted in the generated HTML), it will help you catch other possible invalid uses of HTML which may render as intended in one browser while rendering terribly in another. HTML rendering engines employ many tricks to try and make invalid HTML look okay.
Anyway, all things aside (such as, assuming accept(...) exists, and all other calls in the tag are correct) I think the issue you are having is as follows:
onclick='<%# String.Format("accept('{0}','{1}','{2}','{3}-{4}');", ... )%>'
This line is probably going to evaluate to look something like this:
onclick='accept('{0}','{1}','{2}','{3}-{4}');'
With all single quotes, all the onclick attribute will see is onclick='accept(' which is not a valid javascript method call. You're going to want to use the "" strings, which you can embed in the format string by escaping them.
String.Format("accept(\"{0}\",\"{1}\",\"{2}\",\"{3}-{4}\");", ... )
Then, you should be able to get the correct combination of ' and " within the attribute:
onclick='accept("{0}","{1}","{2}","{3}-{4}");'

Related

How display data generated by Rich Text Editor in ASP.NET MVC? [duplicate]

I have a controller which generates a string containing html markup. When it displays on views, it is displayed as a simple string containing all tags.
I tried to use an Html helper to encode/decode to display it properly, but it is not working.
string str= "seeker has applied to Job floated by you.</br>";
On my views,
#Html.Encode(str)
You are close you want to use #Html.Raw(str)
#Html.Encode takes strings and ensures that all the special characters are handled properly. These include characters like spaces.
You should be using IHtmlString instead:
IHtmlString str = new HtmlString("seeker has applied to Job floated by you.</br>");
Whenever you have model properties or variables that need to hold HTML, I feel this is generally a better practice. First of all, it is a bit cleaner. For example:
#Html.Raw(str)
Compared to:
#str
Also, I also think it's a bit safer vs. using #Html.Raw(), as the concern of whether your data is HTML is kept in your controller. In an environment where you have front-end vs. back-end developers, your back-end developers may be more in tune with what data can hold HTML values, thus keeping this concern in the back-end (controller).
I generally try to avoid using Html.Raw() whenever possible.
One other thing worth noting, is I'm not sure where you're assigning str, but a few things that concern me with how you may be implementing this.
First, this should be done in a controller, regardless of your solution (IHtmlString or Html.Raw). You should avoid any logic like this in your view, as it doesn't really belong there.
Additionally, you should be using your ViewModel for getting values to your view (and again, ideally using IHtmlString as the property type). Seeing something like #Html.Encode(str) is a little concerning, unless you were doing this just to simplify your example.
you can use
#Html.Raw(str)
See MSDN for more
Returns markup that is not HTML encoded.
This method wraps HTML markup using the IHtmlString class, which
renders unencoded HTML.
I had a similar problem with HTML input fields in MVC. The web paged only showed the first keyword of the field.
Example: input field: "The quick brown fox" Displayed value: "The"
The resolution was to put the variable in quotes in the value statement as follows:
<input class="ParmInput" type="text" id="respondingRangerUnit" name="respondingRangerUnit"
onchange="validateInteger(this.value)" value="#ViewBag.respondingRangerUnit">
I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.
I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.
So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.
I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.

how to replace single quote with string in javascript

I have some data from a lookup like this: =winz\ach'dull.
How can I replace single quotes (') with ("").
This is my code =>
<input type="button" id="btnSelect" onclick="Select('<%#Eval("LoginName").ToString().Replace("'", "\'")%>');" value="Select"/>
I'm trying to create code like this:
Select('<%#Eval("LoginName").ToString().Replace("'", "\'")%>');
but it does not not work.
Please correct and help me. Thanks.
In pure javascript we could do :
var a="winz\ach'dull.";
alert(a.replace("'",'"'));
And that would replace your single quote.
Note: Your code is C# not javascript.
You can escape quotes with the "\" character and it works perfectly with HTML. So the answer to exactly what you wrote would be: (this is just to humour you in the future)
"Select('<%#Eval(\"LoginName\").ToString().Replace(\"'\", \"\'\")%>');"
But you have syntax errors in what you are writing and that Eval stuff is not javascript so I don't know why ToString and Replace are attached to it. I've changed it a little based on guessing what you're trying to do:
<input onclick="Select('<%#Eval("LoginName")%>').ToString().Replace(\"'\", \"'\");">
Note that if you're using C# or something on the server side it doesn't need to be escaped because by the time the HTML is parsed in the DOM, typically a browser the source no longer contains your server side code and only the output!

Why do certain tags go a new line when using HtmlTextWriter?

I'm having a bit of a hard time trying to format my HTML when using HtmlTextWriter. It seems that some tags will automatically go to a new line and some won't.
Is there a way to stop this from happening so all tags are created equally and leave the formatting completely up to me?
In my particular case I'm building out a <ul>'s and <li>'s for a custom HTML Sitemap.
The immediate tag that comes after an <ul> will wrap to a new line.
This is not the case for a <li> tag.
If anyone needs clarification please ask question.
Are you using RenderBeginTag? That method will handle some things automatically, and among other things, it will put line breaks (and indentation) in elements that aren't inline (e.g. ul versus span).
If you want to do the rendering manually, use WriteBeginTag("ul") or WriteFullBeginTag("ul") instead.
Note that WriteBeginTag will still handle indentation. However, you have full control over that if you only use the WriteXXX methods.
In the end, though, do those endlines really bother you at all? You do use compression, right? The overhead usually isn't very significant...

How can I check for any html <script> tags in C#, plus anything else nasty?

A user is allowed to format their html in a textbox. This then gets sent to the backend where it will be validated. Other users may then see this textbox.
I want to check for any tags in the backend. I know this can be done with a relatively simple regex. I would just do something like <\s*?script\s*?>
My issue though is if someone does something like this:
test
This would pass validation. I could also make the regex check for onClick, but I'm sure there are other ways around this.
My question: Is there a good way to do this? Am I just going to have to rely on regexes and my own research to figure out how else they could run a script?
EDIT
I suppose I could create a whitelist of what they can enter. It's primarily meant for formatting text, so <b>, <i>, <h> etc. This may or may not be an acceptable solution though, I need to look and see what the actual use case is. I'm hoping there's a different solution to this.
Really you should use white-list validation (i.e. allow only specific examples that you know are safe) rather than trying to detect and remove potentially hazardous input.
One really nice way to do this is to use Markdown rather than just allowing HTML input.
There are OWASP Guidelines for HTML injection.
A simple for removing all HTML tags from content
public string Strip(string text)
{
return Regex.Replace(text, #”<(.|\n)*?>”, string.Empty);
}

why does MS anti xss library (v4) remove html 5 data attributes

AntiXss library seems to strip out html 5 data attributes, does anyone know why?
I need to retain this input:
<label class='ui-templatefield' data-field-name='P_Address3' data-field-type='special' contenteditable='false'>[P_Address3]</label>
The main reason for using the anti xss library (v4.0) is to ensure unrecognized style attributes are not parsed, is this even possible?
code:
var result = Sanitizer.GetSafeHtml(html);
EDIT:
The input below would result in the entire style attributes removed
Input:
var input = "<p style=\"width:50px;height:10px;alert('evilman')\"/> Not sure why is is null for some wierd reason!<br><p></p>";
Output:
var input = "<p style=\"\"/> Not sure why is is null for some wierd reason!<br><p></p>";
Which is fine, if anyone messes around with my code on client side, but I also need the data attribute tags to work!
I assume you mean the sanitizer, rather than the encoder. It's doing what it's supposed to - it simply doesn't understand HTML5 or recognise the attributes, so it strips them. There are ways to XSS via styles.
It's not possible to customise the safe list either I'm afraid, the code base simply doesn't allow for this - I know a large number of people want those, but it would take a complete rewrite to support it.

Categories