Enrutamiento ASP.NET MVC. Espacios en blanco y categorías

I've got a main navigation and one of its list items renders an action:

[ChildActionOnly]
public ActionResult BuildMenu(String category = null) {
    ViewBag.SelectedCategory = category;
    return View("~/Views/Article/CategoriesList.cshtml", this.GetItems());
}

Dónde GetItems el método es:

[NonAction]
public IEnumerable<String> GetItems() {
    return this.session.Query<Article>()
        .Select(x => x.Category)
        .Distinct().ToList()
        .OrderBy(x => x);
}

When posting an Article one can specify category like this: Fringe Division. So in address bar it looks like Fringe%20Division.

Inside a view (menu partial) I have this:

@model IEnumerable<String>
@{ Layout = null; }

<ul class="transparent-custom">
@foreach(var link in Model) {
    <li>@Html.RouteLink(
        link, 
        new { 
            controller = "Article", action = "Index", 
            category = link
        },
        new {
            @class = link == ViewBag.SelectedCategory ? "selected" : ""
        }
    )
    </li>
}
</ul>

If I apply here something like category = Url.ToUrlFriendly(link) (replacing all unacceptable chars with dashes, or with any other chars) while it looks cool in address bar my controller doesn't recognize the category (and that's obvious: it differs from its original):

public ActionResult Index(String category, Int32? page) {

    // there's no such a category in DB...

    ViewBag.CurrentCategory = category;
    if(category == "All") {
        return View(this.GetAllArticles().ToPagedList(page ?? 1, this.PageSize));
    }
    var entries = this.session.Query<Article>()
        .Where(c => c.Category == category)
        .OrderBy(d => d.CreatedOn);
        return View(entries.ToPagedList(page ?? 1, this.PageSize));
    }

How do I handle it the best way? Thanks!

preguntado el 31 de julio de 12 a las 11:07

3 Respuestas

You have to do it also in a reverse order. If you encode something (say replace space with dash) then you have to decode (replace dash with space). Similar to Server.Encode and opposite Server.Decode. Write some Url.DecodeUrlFriendly function. But be careful if your string already contains dash.

Respondido 31 Jul 12, 11:07

I think the best thing for this, is to store a url-friendly category url part, e.g., for Fringe Division, usa algo como fringe-division, which is stored alongside the category information. That way, it persists for the category in the database and uri.

You can make the generation of this url component part of your CMS if you have one.

Respondido 31 Jul 12, 11:07

Typically, you would hold the URL-friendly name of the category as an additional column in the database so you can query against that.

Respondido 31 Jul 12, 11:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.