Sam Alekseev
Sam Alekseev

Reputation: 2391

Prevent URL without protocol to become relative URL

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?

Upvotes: 4

Views: 2222

Answers (2)

hutchonoid
hutchonoid

Reputation: 33306

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")]

Upvotes: 2

CodeCaster
CodeCaster

Reputation: 151604

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/.

Upvotes: 6

Related Questions