Hosea146
Hosea146

Reputation: 7702

MVC 4 - How do I properly execute a URL in a View?

I have an MVC 4 View. One of the properties is 'Url'. I'm displaying the value of the URL in a field in this view and when a user clicks on it, I'd like to execute the URL. I have this code:

<div class="display-label">
     @Html.DisplayName("Url")
</div>
<div class="display-field">
    <a href="@Model.Url">@Model.Url</a>
</div>

The problem is when the user clicks on this URL (I'm using www.microsoft.com as a test), I get the following error:

Requested URL
   http://localhost:52070/HousingBuyerSearch/Details/www.microsoft.com

So it seems I'm doing something wrong because it's attempting to call a method on a controller. I'm still fairly new to all this so I'm not entirely sure how to fix this.

Upvotes: 1

Views: 504

Answers (1)

Nathan Anderson
Nathan Anderson

Reputation: 6878

The problem in this case is your Url does not start with a protocol (IE http://) - so the browser is interpreting this as a relative url to your document. You'll want to add some logic to your app to ensure that external urls start with a protocol, something like this:

var url = "www.microsoft.com";
if (!string.IsNullOrWhiteSpace(url) && !url.StartsWith("http://")) {
    url = "http://" + url;
}

Upvotes: 4

Related Questions