0

Please i am trying to generate my Url hyperlink dynamically in my MVC Application.

<a href='http://facebook.com/myPage'>Facebook</a>

The above link takes me to my facebook home page. I want to be able to change the url later on as the page name is not decided. So i tried

<a href='@Url.Action("GetFaceBookLink", "Home")'>Facebook</a>

And in my controller

 public ActionResult GetFaceBookLink()
        {
            string facebook = repository.SystemSettings.FirstOrDefault().FacebookLink;

            return this.Content(facebook);
        }

My string facebook = "http://facebook.com/mypage" . I want to be redicted to my facebook home page as usal. However, when i clicked, it returns the string url in a black pagewithout redirecting . Please how do i redirect ? how do i achieve this ? Any help would be appreciated.

6
  • You need custom helper Commented Apr 11, 2015 at 10:33
  • @EhsanSajjad I am confused for the url string is returning . Please any tutorial, link or help with the custom helper ? Commented Apr 11, 2015 at 10:34
  • You can create a partial view and use RenderAction to render it on main view Commented Apr 11, 2015 at 10:36
  • 1
    You can do this as well: <a href='@Html.Action("GetFaceBookLink", "Home")'>Facebook</a> Commented Apr 11, 2015 at 10:39
  • Brilliant. It works . But just curious why did Html.Action works and Url does'nt ? I though because we are dealing with url here so Url.Action should do the trick ? Commented Apr 11, 2015 at 10:49

2 Answers 2

2

You need Html.Action helper here :

<a href='@Html.Action("GetFaceBookLink", "Home")'>Facebook</a>

Url.Action do not calls action, it generates url using Controller and Action name

Sign up to request clarification or add additional context in comments.

Comments

2

You can redirect to another site from controller by

public ActionResult GetFaceBookLink() {
return Redirect("http://facebook.com/mypage");
}

2 Comments

But i coudn't use Redirect("http://facebook.com/mypage") for my case though. I got the error Child actions are not allowed to perform redirect actions," . I am doing this in my Layoutpage . A page body has been rendered already and now a controller returning a redirect , i guess thats why the error. Nonetheless , it's a great solution. Thank you :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.