MailTo link in Razor - asp.net-mvc-3

How do I make a mailto link using Razor?
I've seen Html.MailTo, but when I try #Html.MailTo nothing comes up.
Thanks!

You should just make a normal hyperlink:
...
Razor and MVC helper methods are not intended to replace HTML tags; they're intended to make common data-bound elements simpler.

HTML.MailTo() helper is a part of the 'mvc3 futures' project, but there is an alternative to way to do it.
1.)Create a new .cshtml file inside App_Code directory and name it as you want (for example HTMLHelpers.cshtml)
2.)Write the following in the file
#helper EmailTextBox(string email, string title) {
#title
}
3.)Now in your view you can call your new function. For example write
Email: #HTMLHelpers.EmailTextBox("george#example.com","George Chatzimanolis")

I get to this question when I was trying to do simple
Email
but Razor will treat this as text
I know there are HtmlHelpers and such but so far simple code worked for me
Email
Whether a variable comes from model or ViewBag it's about # sign in href and Razor

The mailto helper is a part of the 'mvc3 futures' project.
The below blog will give you more information on mvc3 futures as well as the link to get it. I believe that it is also available as a NuGet package.
http://weblogs.asp.net/imranbaloch/archive/2011/07/26/using-the-features-of-asp-net-mvc-3-futures.aspx

#{var email= new HtmlString( "" mail me ""));}
#email;

Related

ASP.NET Core MVC : Razor pages routing, incorrectly re-using previous route data

I'm working on a dotnet 6 mvc application using RazorPages, and I'm having a problem with strange routing behavior.
I have a RazorPage /Pages/News.cshtml
This page is accessible using the default route /news
When called without any parameters this page will display an index of news articles.
I also want this page to be able to display a specific news article, via a path like this...
/news/1234-my-news-article
To achieve this, I've added a config like so...
builder.Services.AddRazorPages(options =>
{
options.Conventions.AddPageRoute("/News", "News/{id:regex(^\\d+\\-.*)?}");
});
In my templates, I can then use links like this...
<a asp-page="/News" asp-all-route-data="#(new Dictionary<string, string> { { "id", "1234-my-news-article" } })">My News Article</a>
or
<a asp-page="/News">All Articles</a>
However, once I've navigated to a specific article, the index link doesn't render correctly, and will instead link again to the same article. It appears to be re-using the current routing parameters.
Is there some way to avoid this?
update:
I've found a work-around, if I use this tag instead...
<a asp-page="/News" asp-route-id="">All Articles</a>
then it will link correctly to "/news".
It seems a bit counter-intuitive to have to explicitly set this to blank. I would have assumed it would default to unset, unless explicitly set otherwise.
This is known as ambient route values (https://www.learnrazorpages.com/razor-pages/tag-helpers/anchor-tag-helper#ambient-route-values), where the current route values are automatically added to outbound links which are generated by the anchor tag helper if the destination page is the same as the current page. In older versions of Razor Pages, this was the default behaviour for all pages.
As you have discovered, you can override this by setting the route value to an empty string, or as suggested elsewhere, to use a plain anchor tag for your link.
asp-page tag helper will add id value to the route by default.It is by design.If you don't want to add it,you can try to use href to replace asp-page:
All Articles

How do you format localized strings to have single words of a sentence be a link?

I am working on a globalized web-app in ASP.NET MVC3. The project contains the I18N resources files and I normally access the resources inside my Razor views like...
#I18N.MyResourceString
I have a tricky situation which I have not been able to figure out a elegant solution to yet. I need to be able to localized the sentence "Click here to donate." where the word 'here' should be a link to our donation system.
Most links in the site are internal so to create link I simply write...
#Html.ActionLink("Some link text", "MyAction", "MyController")
This donation link is external. What I have so far (which is not working) is...
#String.Format(I18N.ClickHereToDonate, "" + I18N.Here + "")
where the I18N.ClickHereToDonate resource's text is "Click {0} to donate.".
What I see on the screen is...
Click here to donate.
Furthermore, I would also like to add a 'title' attribute to the 'a' tag. It gets even uglier when I try that...
#String.Format(I18N.ClickHereToDonate, "" + I18N.Here + "")
There has to be a better way to form complex strings with embedded tags without concatenating things together in such a hackish manner. Not only does it not work (the intended markup got encoded) but it makes the HTML inside a string literal in my razor template which makes me loose any awesome IDE support/intergation/refactoring capabilities.
How can markup be injected into localized strings?
UPDATE
Adam Tuliper mentioned the #Html.Raw helper method in his answer so I added it to my already ugly markup...
#Html.Raw(String.Format(I18N.ClickHereToDonate, "" + I18N.Here + ""))
This at least got me a click-able link in the outputted markup.
Click here to donate.
It is still a far-less-than-elegant solution though so I am still looking for better ways of doing this.
Maybe try
#I18N.ClickHereToDonate
Overall, you don't need the String format - you can just inject the Razor things inside normal html elements.
Edit: Incorporating the below:
#Html.Raw(String.Format(#I18N.ClickHereToDonate,String.Format("<a href='http://paypal.com' title='{0}'>{1}</a>", I18N.PayPal,I18N.Here)))
Your choices are limited without built in support for this scenario (and there isn't in the helpers)
The cleaner way is to form your urls in a viewmodel and pass that view model to the view so you have minimal html. Your ViewModel contains
public class WhateverIndexViewModel
{
public string Key {get;set;}
public string URI {get;set;}
public string Title {get;set;}
}
Set the info in your controller, pass it to your view and use
#Links["YourKey"].Title"
As a basic idea.
Note if you dont want to use Html.Raw here then your URI in the class would be of type MvcString not String this way #Links["YourKey"].URI won't be html encoded.

[Display(Prompt MVC3

I am trying to setup my model so I can use the
#Html.EditorFor(e => e.publicationTitle) and have it show a Watermark with a hint.
Currently I am doing
#Html.LabelFor(e => e.PublicationTitle) #Html.TextBox("PublicationTitle",tempTitle.ToString(), new { style = "width:350px", placeholder = "Put title here" })
#Html.ValidationMessageFor(e => e.PublicationTitle)
I have found that you can put a [Display(Prompt="Enter title here")] in my model
but it is not showing up in my view for some reason.
On a side note. I did try to follow the instructions from this post
Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?
At the end of this post it says to change the ~/Views/Shared/EditorTemplates/String.cshtml file but this file is not located in my project.
Any hints would be appreciated. Thank you in advance.
FOLLOW UP!
Ah the joys of MVC3. Apparently the above post answers the question once you understand what is going on. If you create the EditorTemplates/String.cshtml file in your ~/Views/Shared/ folder then it will use this template for your editfor boxes.
Final Answer to be concise for others looking will be posted below.
In your controller you need to do the following
[Display(Prompt="First Name Goes Here",Name="First Name")]
[StringLength(100,ErrorMessage="First Name may not be longer than 100 characters")]
public string AuthFirstName { get; set; }
The Prompt="This is what will display" under display is the watermark that will be created.
Then you will need to create the folder "EditorTemplates" under ~/Views/Shared the entire path will be ~/Views/Shared/EditorTemplates/
Then create the file String.cshtml and place the following code in it
#Html.TextBox("",ViewData.TemplateInfo.FormattedModelValue, new { #class="text-box single-line", placeholder = ViewData.ModelMetadata.Watermark })
More detailed information can be found at the link posted by tugberk (SO question and SO answer).
This will not work with IE unfortunately. At least IE9 and earlier. I spent couple hours pulling my hair as to why this helped others and doesn't work here. Apparently IE won't show prompts. Hope IE10 will address the issue.
The placeholder attribute is not supported in earlier versions of IE, so for the Display[(Promt="...")] to work fine I recommend to use (along with the String template as Samack described) any jQuery watermark plugin (I used the google one) then add this to the Document.Ready function:
$(document).ready(function(){
$(':text').watermark({ textAttr: 'placeholder' });
})

create custom controls mvc3

Just starting to get the hang of MVC3 and want to start building out some custom controls that I can just drop into a view. Specifically I want to be able to drop in some html form controls that will automatically add some javascript for validation.
something like this is what I'd want:
#Html.VTextBox("MyTextBox","",new {#vType="PhoneNumber", #vMessage="You Must Enter a Phone Number" })
when the page is rendered, I'd want it to search for any custom elements I create then drop in the appropriate javascript to validate client side. I did something very similar to this with asp.net web forms for custom controls ie
<ucc:VTextBox ID="MyTextBox" runat="server" message="You must fill this in" />
just wondering if MVC3 offers the same extensibility. Any resources or advice you can provide would be greatly appreciated.
TIA
To start off with, you'll need to look into extension methods and more specifically, how to create extension methods for the HtmlHelper class so you could write code like the example you've shown above.
For the example you've shown above, you could write code like this:
public MvcHtmlString VTextBox(string name, object value, object htmlAttributes)
{
StringBuilder html = new StringBuilder();
// Build your html however you want
// Here's a simple example that doesn't
// take into account your validation needs
html.AppendFormat("input type=\"text\" name=\"{0}\" value=\"{1}\" />", name, value);
return MvcHtmlString(html.ToString());
}
Then in your view you can use the example above like so:
#Html.VTextBox("MyTextBox","",new {#vType="PhoneNumber", #vMessage="You Must Enter a Phone Number" })
NOTE: You'll need to import the namespace the extension method is in to your view. Simplest method, put a #using ExtensionMethodNamespace at the top of your view. You can make the namespace automatically imported to all your views by fiddling with the web.config (and maybe the Global.asax).
ADDENDUM: Please note RPM1984's comment below where he advises to use TagBuilder in place of StringBuilder which is sound advice since this is the exact scenario TagBuilder was designed for. He also mentions strong typing the helper to the model which is also great advice.

Is it possible to display raw Html from database in ASP.NET MVC 3?

I have a table in my db where one of the properties is an Html page (without the html, head and body tags), and I intend to put it in the middle of one of my views - say, I call a cotroller method that takes an argument, and return a view passing this html big string as the model. I searched for it (not much, I admit), and found the following method:
<%= System.Web.HttpUtility.HtmlDecode(yourEncodedHtmlFromYouDatabase) %>
That was found here in stackoverflow. When I tried a similar razor aproach, I ended up with this:
#System.Web.HttpUtility.HtmlDecode("<h1>Test</h1>")
That's the idea, but it didn't work quite as I planned.
All you need is: #Html.Raw(yourEncodedHtmlFromYouDatabase)
I'm assuming that the html in the database has been properly sanitized (or at least from a reliable source), because if not, you could be opening yourself up to cross-site scripting attacks.
The reason your approach didn't work is that Razor HTML-encodes output by default (every time you use # to display something). Html.Raw tells Razor that you trust the HTML and you want to display it without encoding it (as it's already raw HTML).
You can also return a HTMLString and Razor will output the correct formatting, for example.
#Html.GetSomeHtml()
public static HtmlString GetSomeHtml()
{
var Data = "abc<br/>123";
return new HtmlString(Data);
}
This will allow you to display HTML

Resources