zSynopsis
zSynopsis

Reputation: 4854

Rewriting the URL for a Controllers Action Method

I have a controller called Person and it has a post method called NameSearch.

This method returns RedirectToAction("Index"), or View("SearchResults"), or View("Details"). The url i get for all 3 possibilities are http://mysite.com/Person/NameSearch. How would i change this to rewrite the urls to http://mysite.com/Person/Index for RedirectToAction("Index"), http://mysite.com/Person/SearchResults for View("SearchResults"), and http://mysite.com/Person/Details for View("Details").

Thanks in advance

Upvotes: 1

Views: 988

Answers (1)

Matthew Abbott
Matthew Abbott

Reputation: 61617

I'm assuming your NameSearch function evaluates the result of a query and returns these results based on:

  1. Is the query valid? If not, return to index.
  2. Is there 0 or >1 persons in the result, if so send to Search Results
  3. If there is exactly 1 person in the result, send to Details.

So, more of less your controller would look like:

public class PersonController
{
  public ActionResult NameSearch(string name)
  {
    // Manage query?
    if (string.IsNullOrEmpty(name))
      return RedirectToAction("Index");

    var result = GetResult(name);
    var person = result.SingleOrDefault();
    if (person == null)
      return RedirectToAction("SearchResults", new { name });

    return RedirectToAction("Details", new { id = person.Id });
  }

  public ActionResult SearchResults(string name)
  {
    var model = // Create model...

    return View(model);
  }

  public ActionResult Details(int id)
  {
    var model= // Create model...

    return View(model);
  }
}

So, you would probably need to define routes such that:

routes.MapRoute(
  "SearchResults",
  "Person/SearchResults/{name}",
  new { controller = "Person", action = "SearchResults" });

routes.MapRoute(
  "Details",
  "Person/Details/{id}",
  new { controller = "Person", action = "Details" });

The Index action result will be handled by the default {controller}/{action}/{id} route.

That push you in the right direction?

Upvotes: 1

Related Questions