Outputting formatted code to view in asp.net MVC - c#

I am hoping there is a solution to this,
I have an example MVC application, and I want to output formatted snippets of code to the browser
Something like the following
ViewBag.PageSource = "
public class RegisterViewModel
{
[Required]
[Display(Name = "User name")]
[RegularExpression("[a-zA-Z0-9]{2,64}", ErrorMessage = "username must contain letters or numbers only, and be between 2 and 64 characters long ")]
public string UserName { get; set; }
}
";
Is this sort of thing possible ?
I have a modal popup in the main layout file and I wanted this to contain the source (model/controller) snippets for each view, by placing it in a viewbag variable in each view

Don't try to do this at the controller. That's what the view is for.
code.google.com & Stackoverflow use Code-Prettify.
You can then use it with the pre tags:
<pre class="prettyprint">
public class RegisterViewModel<br/>
{<br/>
[Required]<br/>
[Display(Name = "User name")]<br/>
[RegularExpression("[a-zA-Z0-9]{2,64}", ErrorMessage = "username must contain letters or numbers only, and be between 2 and 64 characters long ")]<br/>
public string UserName { get; set; }<br/>
<br/>
}<br/>
</pre>

Yes, anything is possible. Add the # sign in front of first " and multi-line strings will work.
Then you need to do something about the tabs. You could use <pre> tag or replace tabs with a fixed-width div.

If snippet is dynamicly generated you have to use JavaScript formatted.
For example
SyntaxHighlighter is good client-side solution:
http://alexgorbatchev.com/SyntaxHighlighter/
In other case take a look here
Jon Skeet provides a code formatter for public use:
http://csharpindepth.com/CodeFormatterTool.aspx
UPDATE
Seems to me that SO use this https://code.google.com/p/google-code-prettify/

For HTML5 you should use <pre><code>//your code here</code></pre>.

Related

ASP.NET MVC & C# : better Dollars and Cents data entry

Is there a way to better control the user experience of Html.TextBoxFor?
I currently have:
#Html.TextBoxFor(m => m.TotalDue,
new { #id = "TotalDue", #class = "decimal_input", #dir = "rtl" })
And a model of:
public decimal TotalDue { get; set; }
When a user comes to that field, if a 0 is displayed and the user begins to type his/her dollar amount, the leading zero stays there. When the user leaves the field, the amount is not formatted.
Ideally, I would like the user to come to the field and if they typed 123456.78 and then pressed TAB to the next field, it would display 123,456.78. If they type 123456, it would display 123,456.00. It would be best if it formatted as they typed, although I could live with just making the field pretty when they leave the field.
I have experimented with Html.EditorFor, but haven't found the right combination. I am open to using that or a "helper" of some sort. I would like the user to have the same experience as found in PDF forms, or something close to it.
Try this: imask.js. I've done a jsfiddle to demonstrate here, and a .NET fiddle here.
Include <script src="https://unpkg.com/imask"></script> on your page and then this script:
var totalDueMask = IMask(
document.getElementById('TotalDue'),
{
mask: '$num',
blocks: {
num: {
mask: Number,
radix: '.',
thousandsSeparator: ','
}
}
}
);
I've formatted it for USD but you can adjust the settings to suit - all the options are documented on the IMask site.

Selenium c# Unable To Get Test To Fail When Looking For Text

I am validating the presents of text within an address field and the text is present but no matter what I put in the expected string the test passes
string AddressLine1 = YourDetails.AddressLine1.GetCssValue("The Big Test House");
Another input element I am trying to retrieve text from:
<input id="first_name_text_box" name="firstName" class="StyledInput-sc-1p20bfl iaFJkJ" value="Cal">
If you want to get an element's text, you should use .Text instead.
So you would use:
string AddressLine1 = YourDetails.AddressLine1.Text;
Assuming YourDetails.AddressLine1 is a WebElement.
This seems to be the conclusion
Assert.AreEqual(Addresses.AddressLine1 .GetAttribute("value"), "My House");
Addresses.AddressLine1 is derived from the POM, which looks like this for those wondering -
Namespace - Addresses
public IWebElement AddressLine1{ get { return driver.FindElement(By.id='first_line_of_address']")); } }

How do I make a Html textbox to only take integer in Razor MVC?

Haven't been able to find a good answer to my situation yet. I want this textbox to only take numbers and still have the id "SearchString2" so I can use it in my controller. Any idea how?
if (Roles.IsUserInRole(WebSecurity.CurrentUserName, "Admin"))
{
#:<p><b>Customer ID:</b> #Html.TextBox("SearchString2")</p>
}
Thanks in advance.
You can do something like this:
#Html.TextBox('SearchString2', new { #type = "number" })
This should set the type to be a number, you could then use attributes on your model to help limit it to only ints like so:
[RegularExpression(#"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
public string SearchString2 { get; set; }
You'll need to replace the regex with an actual regex and put an validation message in.
Here's more info on validation: http://www.asp.net/mvc/overview/getting-started/introduction/adding-validation
Actually, I think the correction needed to the above answer is
#Html.TextBox('SearchString2',null, new {#type="number"})
otherwise type=number shows up in the value.

Assignation of string with accents to another string, replaces them with "&#243;"

I have a list of elements, and one of those elements field is a string value that contains an spanish-accented text which I see ok in the list.
Once I enter de Detail page for one of those elements, the accents are shown like this ó
I have a string variable that contains the original Spanish-Accented text, and I assign that value to the new view.
Example:
string a = "facturación";
view.Document = a;
and the field a of the class view is declared like this:
string Document { get; set; }
when I do a quickwatch over "a" I see "facturación".
when I do a quickwatch over "view.Document" y see "facturaci&#243;n"
what can I do?
Thanks in advance!
Found the error!
The property was re-defined like this:
public string Document
{
get
{
return HttpUtility.HtmlEncode(txtDocument.Text);
}
set
{
txtDocument.Text = HttpUtility.HtmlEncode(value);
}
}
So the HtmlEncoding was the thing that was messing up with my string.
Thanks anyway!
The reason this happens is that the view is escaping the string before rendering it. Use
<%= Server.HtmlDecode(mystring) %> in your view to render the string un-escaped.

Url mapping in web forms - allow question marks and hyphens

I have implemented URL mapping in our ASP.NET 4 application, but I have a problem with some of our content.
Some of our products has a hyphen "-" or a question mark "?" in them. It's not an option to remove that. A productname could be "My Product - Good for you?".
We use two custom made methods, MakeUrlSeoReady and MakeUrlNonSeoReady. We replace space like this: Replace(" ","-"), as this is the most SEO-friendly solution. However, we also need to make this work with both question marks and hyphens.
The reason we use the MakeUrlSeoReady / NonReady methods is to be able to show the "real" name.
Currently the mapping is defined as follows:
routes.MapPageRoute("Produkt visning",
"artikler/{Categoryname}/{SubCategoryname}/{ProductName}",
"~/SingleProduct.aspx");
So what I do is I retrieve the product depending on the ProductName. I use two methods I've created:
public static string MakeUrlNonSeoReady(string text)
{
return text.ToLower().
Replace("oe", "ø").
Replace("aa", "å").
Replace("ae", "æ").
Replace("-", " ");
}
public static string MakeUrlSeoReady(string text)
{
return text.ToLower().
Replace("ø", "oe").
Replace("å", "aa").
Replace("æ", "ae").
Replace(" ", "-");
}
So in the SingleProduct.aspx page I use the following string to get from our database:
string categoryName = HelperFunctions.MakeUrlNonSeoReady(Page.RouteData.Values["ProductName"]);
But this will of course not work. So any help is really appreciated :-)
An arguably cleaner and simpler method is to use a unique product identifier that is numerical or alphanumerical and is natively HTML encoded, and then simply put the product name as an unused parameter for SEO or search purposes.
MSDN RouteCollection.MapPageRoute Method (String, String, String, Boolean, RouteValueDictionary)
routes.MapPageRoute("Produkt visning",
"artikler/{Categoryname}/{SubCategoryname}/{ProductIdentifier}/{ProductName}",
"~/SingleProduct.aspx", false, new RouteValueDictionary
{ { "ProductName ", string.Empty } });

Categories

Resources