I have some model and I want to render html-markup in RazorView like this:
<a href="@Model.Website">@Model.Title</a>
The user can write any url in the Website
property (google.com
, www.google.com
, http://www.google.com
etc).
The problem is if the user doen't write the protocol prefix, like http
, then the resulting HTML is seen as a site-relative URL by the browser:
<a href="http://localhost:xxxx/google.com">Google</a>
Is there any simple solution or do I have to prepare website string (add "http" prefix) before rendering the html?
This isn't really MVC specific, but you could use the UriBuilder
class:
string uri = "http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx";
var uriBuilder = new UriBuilder(uri);
uriBuilder.Scheme = "http";
Console.WriteLine(uriBuilder.Uri);
Prints http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx
.
string uri = "google.com";
var uriBuilder = new UriBuilder(uri);
uriBuilder.Scheme = "http";
Console.WriteLine(uriBuilder.Uri);
Prints http://google.com/
.
You can use the [Url]
attribute for this to enforce users to enter a correct Url.
Add this to your model:
[Url]
public string Website { get; set; }
And this to your view.
<div class="editor-field">
@Html.EditorFor(model => model.Website)
@Html.ValidationMessageFor(model => model.Website)
</div>
You can specify a specific message back to the users like this:
[Url(ErrorMessage = "You must specify the full url including the protocol i.e. http://www.google.com")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With