Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 504
Sam Alekseev Avatar asked Feb 14 '23 00:02

Sam Alekseev


2 Answers

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

like image 177
CodeCaster Avatar answered Feb 24 '23 00:02

CodeCaster


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")]
like image 31
hutchonoid Avatar answered Feb 23 '23 23:02

hutchonoid