Ad

ASP.NET Mvc 5 Return View With Seo Friendly Url

I'm looking for a way to return a View based on an Id, but adding a friendly url part when returning.

I know I can pass in the id and name when I have this data available, e.g. by using:

Url.Action("Index", "Cat", new { id = model.ID, seoname = model.SEO });


[AllowAnonymous]
[Route("Cat/{id?}/{seoname?}")]
public ActionResult Index(int? id = null, string seoname = null) {
   // do something with id and create viewmodel 

   // in case I get redirect from the SelCat actionresult:
   if (id.HasValue and string.IsNullOrEmpty(seoname)) { 
      // look in the database for title by the given id
      string seofriendlyTitle = ...;
      RouteData.Values.AddOrSet("seoname", seofriendlyTitle);
   }

   return View(viewmodel);
}

this code above is not a problem. The problem occurs when I submit a form (dropdownlist) where I only have the Id available.

[HttpPost]
[AllowAnonymous]
[Route("Cat/SelCat/{form?}")]
public ActionResult SelCat(FormCollection form) 
{ 
   string selectedValues = form["SelectedCat"];
   // ...
   int id = selectedCatID;
   return RedirectToAction("Index", new { id = id });
} 

In case I redirect from the SelCat action to the Index action with only an ID I want to search the seofriendly name and when returning the view. I was hoping that the url had the friendly url part.

   // in case I get redirect from the SelCat actionresult:
   if (id.HasValue and string.IsNullOrEmpty(seoname)) { 
      // look in the database for title by the given id
      string seofriendlyTitle = ...;
      RouteData.Values.AddOrSet("seoname", seofriendlyTitle); // <-- does not alter url
   }

How can I make my url seo friendly when returning a View in my Controller Action when only an ID is given?Setting the RouteData.Values. does not seem to add the part to the url.

Ad

Answer

You will have to look in the database for the SEO friendly slug before redirecting and include it in the url, otherwise it's too late:

[HttpPost]
[AllowAnonymous]
[Route("Cat/SelCat/{form?}")]
public ActionResult SelCat(FormCollection form) 
{ 
    string selectedValues = form["SelectedCat"];
    // ...
    int id = selectedCatID;

    // look in the database for title by the given id
    string seofriendlyTitle = ...;
    return RedirectToAction("Index", new { id = id, seoname = seofriendlyTitle });
}

Once you have reached the Index action it is already too late to be able to alter the url that is shown on the client, unless you make an additional redirect (which of course would be insane).

Ad
source: stackoverflow.com
Ad