When I use & operand in html textarea, it doesn't appear - c#

I have a text area field as shown below, when I enter a string like that : testing123!&aaa it only returns testing123!
<span class="value">
#Html.TextAreaFor(m => m.Nr2FieldComment, 4, 43, new { #class = "" })
</span>

I'm assuming you're having this issue with your ajax request, if true, please use encodeURIComponent like bellow;
var commentClean = encodeURIComponent(comment);

The '&' character has special meaning as the lead character in specifying special character values. Use & instead and it should appear. Lookup all the special character codings to see how and when you need this notation.

Related

Limiting length of a phone number

I want a field for a phone number to take in a maximum of 10 digits. I have the [stringlength] attribute placed but I still cannot get the desired result. Thanks to those that can help me.
On a side note, is it possible to break apart the phone number so that the area code and the remaining digits get sent out separately to a db via a stored proc?
model:
public class Pharmacy
{
[StringLength(10,MinimumLength=10)]
public string PhoneNumber
{
get
{
return _phoneNumber;
}
set
{
Regex regexObj = new Regex(#"[^\d]");
_phoneNumber = regexObj.Replace(value, "");
_phoneNumber = Regex.Replace(_phoneNumber, #"(\d{3})(\d{3})(\d{4})", "($1) $2-$3");
}
}
}
form field:
<label id="lblPhoneNumber">Phone Number</label>
<input style="margin: 5px; " type=text name="txtPhoneNumber" id="txtPhoneNumber" value="#Model.Pharmacy.PhoneNumber" />
Why are you using HTML tags for the input if you're using ASP.NET MVC? You should really use Razor tags.
#Html.LabelFor(model => model.PhoneNumber, new { id = "lblPhoneNumber" })
#Html.TextBoxFor(model => model.PhoneNumber, new { id = "txtPhoneNumber", style="margin: 5px;", name="txtPhoneNumber", #Value = Model.Pharmacy.PhoneNumber })
#Html.ValidationFor(model => model.PhoneNumber, "", new { #class = "text-danger" })
Also, make sure you have unobtrusiveJS NuGet UnobtrusiveJS for the validation. Everything else seems fine with the data annotation. The unnamed parameter of [StringLength] is the maximum length, while you need to specify a minimum length. You might also want to let the user know about the error, so you'll need an error message as well [StringLength(10, MinimumLength=10, ErrorMessage="* Must be 10 digits")]
For the second part of the question
On a side note, is it possible to break apart the phone number so that the area code and the remaining digits get sent out separately to a db via a stored proc?
Yes, use RegEx capture groups, which you're already doing :).
RegEx regEx = new Regex(#"(\d{3})(\d{3})(\d{4})")
Matches matches = regex.Matches(value);
// matches[0] contains area code
// matches[1] contains first 3 digits
// matches[2] contains final 4 digits
MSDN - Regex.Matches

How would I Strip Html from a string and set a character limit?

I'm getting a string from a list of items, The string is currently displayed as "item.ItemDescription" (the 9th row below)
I want to strip out all html from this string. And set a character limit of 250 after the html is stripped.
Is there a simple way of doing this?
I saw there was a posts saying to install HTML Agility Pack but I was looking for something simpler.
EDIT:
It does not always contain html, If the client wanted to add a Bold or italic tag to an items name in the description it would show up as <"strong">Item Name<"/strong"> for instance, I want to strip out all html no matter what is entered.
<tbody>
#foreach (var itemin Model.itemList)
{
<tr id="#("__filterItem_" + item.EntityId + "_" + item.EntityTypeId)">
<td>
#Html.ActionLink(item.ItemName, "Details", "Item", new { id = item.EntityId }, null)
</td>
<td>
item.ItemDescription
</td>
<td>
#if (Model.IsOwner)
{
<a class="btnDelete" title="Delete" itemid="#(item.EntityId)" entitytype="#item.EntityTypeId" filterid="#Model.Id">Delete</a>
}
</td>
</tr>
}
</tbody>
Your best option IMO is to night get into a parsing nightmare with all the possible values, why not simply inject a class=someCssClassName into the <td> as an attribute. Then control the length, color whatever with CSS.
An even better idea is to assign a class to the containing <tr class=trClass> and then have the CSS apply lengths to child <td> elements.
You could do something like this to remove all tags (opening, closing, and self-closing) from the string, but it may have the unintended consequence of removing things the user entered that weren't meant to be html tags:
text = Regex.Replace(text, "<\/?[^>]*\/?>", String.Empty);
Instead, I would recommend something like this and letting the user know html isn't supported:
text = text.Replace("<", "<");
text = text.Replace(">", ">");
Just remember to check for your 250 character limit before the conversion:
text = text.Substring(0, 250);
This Regex will select any html tags (including the ones with double quotes such as <"strong">:
<[^>]*>
Look here: http://regexr.com/3cge4
Using C# regular expressions to remove HTML tags
From there, you can simply check the string size and display appropriately.
var itemDescriptionStripped = Regex.Replace(item.ItemDescription, #"<[^>]*>", String.Empty);
if (itemDescriptionStripped.Length >= 250)
itemDescriptionStripped.Substring(0,249);
else
itemDescriptionStripped;

ASP.NET MVC converting a model list of string with spaces into a javascript array

I'm using ASP.NET MVC (with Razor) and JQuery
I have a list of strings in my controller and I render the partial view passing in the model with the below list.
List<string> list = new List<string>();
list.Add("Texas");
list.Add("New York");
On client in my cshtml file side I have:
<div id = "test", test-att = #Html.Raw(Json.Encode(Model.list)) />
In my javascript file I do:
var javascriptArray = JSON.parse($('#test').attr('test-att'));
I get an error "unexpected end of input".
Using Chrome dev tools console I see the following:
$('#test') : <div id ="test" test-att = "["Texas", "New" York"]>
$('#test').attr('test-att') : "["Texas","New"
I'm expecting : "["Texas","New York"]"
Looking like its getting messed up because of the space before being passed in JSON.parse. It seems to stop when it finds a space.
Any ideas on how to fix this?
Put your JSON between single quote NOT double quote characters:
<div id = "test" test-att = '#Html.Raw(Json.Encode(Model.list))' />
Content of cshtml file will be like as bellow
<div id = "test" test-att = "#Html.Raw(Json.Encode(Model.list))" />
There seems to be 2 issues with what you have :
The Json encoder uses " (double quotes) to delimitate strings. It's not gonna work since in XML double quote are used to delimitate attributes.
For this issue you have 2 solutions the easiest one would probably be replacing every " in the Json Encoded string by
<div id = "test", test-att ="#Html.Raw(Json.Encode(Model.list).Replace("\"",""")" />
It seems to me the culprit is #Html.Raw. If you use the following -
<div id='dd' data-att="#Json.Encode(list)">
Then parsing with javascript doesn't fail.
var a = document.getElementById('dd');
JSON.parse(a.dataset.att);
Single quote or double quote doesn't matter. But if you use #Html.Raw then double quote gives you the said error. You can use #Html.Raw against each item of your list instead -
<div id='dd' data-att="#Json.Encode(list.Select(x=> Html.Raw(x).ToHtmlString()).ToList<string>())">
This will work with double quote.

Selenium WebDriver C# - get text

I have this Html element on the page:
<li id="city" class="anketa_list-item">
<div class="anketa_item-city">From</div>
London
</li>
I found this element:
driver.FindElement(By.Id("city"))
If I try: driver.FindElement(By.Id("city")).Text, => my result: "From\r\nLondon".
How can I get only London by WebDriver?
You could easily get by using class-name:
driver.FindElement(By.Class("anketa_item-city")).Text;
or using Xpath
driver.FindElement(By.Xpath("\li\div")).Text;
You can try this:
var fromCityTxt = driver.FindElement(By.Id("city")).Text;
var city = Regex.Split(fromCityTxt, "\r\n")[1];
Sorry for my misleading. My previous provide xpath is which ends in the function /text() which selects not a node, but the text of it.
Approach for this situation is get parent's text then replace children's text then trim to remove space/special space/etc ....
var parent = driver.FindElement(By.XPath("//li"))
var child = driver.FindElement(By.XPath("//li/div"))
var london = parent.Text.Replace(child.Text, "").Trim()
Notes:
If Trim() isn't working then it would appear that the "spaces" aren't spaces but some other non printing character, possibly tabs. In this case you need to use the String.Trim method which takes an array of characters:
char[] charsToTrim = { ' ', '\t' };
string result = txt.Trim(charsToTrim);
This worked for me.
driver.FindElement(By.XPath("//li[#id='city']/text()"));

Show new lines from text area in ASP.NET MVC

I'm currently creating an application using ASP.NET MVC. I got some user input inside a textarea and I want to show this text with <br />s instead of newlines. In PHP there's a function called nl2br, that does exactly this. I searched the web for equivalents in ASP.NET/C#, but didn't find a solution that works for me.
The fist one is this (doesn't do anything for me, comments are just printed without new lines):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace("\r\n", "<br />\r\n");
%>
<%= comment %>
The second one I found was this (Visual Studio tells me VbCrLf is not available in this context - I tried it in Views and Controllers):
<%
string comment = Html.Encode(Model.Comment);
comment.Replace(VbCrLf, "<br />");
%>
<%= comment %>
Try (not tested myself):
comment = comment.Replace(System.Environment.NewLine, "<br />");
UPDATED:
Just tested the code - it works on my machine
UPDATED:
Another solution:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringReader sr = new System.IO.StringReader(originalString);
string tmpS = null;
do {
tmpS = sr.ReadLine();
if (tmpS != null) {
sb.Append(tmpS);
sb.Append("<br />");
}
} while (tmpS != null);
var convertedString = sb.ToString();
to view html tags like a DisplayFor
you need to use another method , in fact the mvc dosent allowed you to view tags in page
but you can used this to ignore this option
#Html.Raw(model => model.text)
good luck
If you have a Razor-based view , string with line breaks and want to show that text with the line-breaks intact in your view, you can do this without replacing all \r\n with "html br"-tags. Instead present the text in an element that has the style property white-space set to pre-line. You should really add a class like:
<span class="line-breaks">#Model.MyText</span>
.line-breaks {
white-space:pre-line;
}
Original Found #
https://kaliko.com/blog/text-line-breaks-in-asp.net-mvc-razor-view/
Please have a look this answer Replace Line Breaks in a String C# here.
#Html.Raw(#Model.Comment.RestoreFormatting())
and than...
public static class StringHelper
{
public static string RestoreFormatting(this string str)
{
return str.Replace("\n", "<br />").Replace("\r\n", "<br />");
}
}
I have the same issue and above all answer given the hint, not exactly help, that's why given the answer to help.
Replace "\n" strign with '', '\r\n','\n', nothing help and finally when replace "\r\n", it will work. (in display it like \n, but in database it store as \\n)
Old code
#Html.TextArea("MEPat_textPatNote", Model.MedicationPatCur, 4, 4, new { #class = "k-textbox", style = "width: 100%;", maxlength = "300" })
New code
#Html.TextArea("MEPat_textPatNote", Model.MedicationPatCur.PatNote== null? "": Model.MedicationPatCur.PatNote.Replace("\\n","\r\n"), 4, 4, new { #class = "k-textbox", style = "width: 100%;", maxlength = "300" })

Categories

Resources