3

Currently I am working with simple Forum module in ASP.NET MVC 3 which i will add later to my main application. The possibility to link to certain blocks like div used to present thread replies is very useful.

I figured out something which work and propably will be enough for my needs, I just wonder if there is something more elegant and simple aswell. I found a solution using ActionFilters, and since I'm quite begginner in MVC I would like to find some easier solution (if exists). Well i will propably learn ActionFilters soon aswell :)

So here is what I've done:

public ActionResult ShowThread(int id, int? postID)
{

    var thread = db.ForumThreads.Find(id);
    if (postID != null)
    {
        return Redirect(Url.Action("ShowThread",new {id=id})+"#post-"+postID.ToString());
    }
    return View(thread);
}

I know it is quite simple, but it is working. Also it doesn't check if the postID is valid yet, but it is not a part of question.

Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
YellowBird
  • 119
  • 4

1 Answers1

0

The solution is to use one of RedirectToAction overloads: http://msdn.microsoft.com/en-us/library/dd470154(v=vs.108).aspx. Perhaps, in your case, the next one would do: http://msdn.microsoft.com/en-us/library/dd460291(v=vs.108).aspx
And the call would be:


    return this.RedirectToAction("ShowThread", new { id = id, post = postID });

Another (simpler, but not safer!) solution is to format the URL you need to redirect to and to use the Redirect() method like this:


    var redirectUrl = string.Format("/Home/ShowThread/{0}?post={1}", id, postID);
    return this.Redirect(redirectUrl);

Pay attention to your URL mappings, though. The examples above assume the method


    public ActionResult ShowThread(int id, int? post)

is in HomeController and the default route has not been changed. Otherwise you should

  1. adjust the URL prepending the controller name (w/o Controller), or
  2. change your default route to map to the controller's name.
Alexander Christov
  • 9,625
  • 7
  • 43
  • 58