user1399217
user1399217

Reputation: 71

Vanity Url, reading an entered string instead of int

I'm trying to allow for Vanity Urls, but I am running into the problem that if I enter

XXXX/User/Profile/Test

instead of

xxxx/User/Profile/224

That it cannot read the string.

My current ActionResult is as follows:

public ActionResult Profile(int ID = -1, string VanityID = null)
    {
        if (VanityID == null)
        {
            ppUser viewerChoice = DB.ppUser_GetUserByPersonID(ID);
            return View(viewerChoice);
        }
        else
        {
            ppUser viewerChoice = DB.ppUser_GetUserByVanityID(VanityID);
            return View(viewerChoice);
        }
    }

It will take in int Id if an int is entered into the URL, but if a string is entered nothing is taken in and it throws an error because the ID is read as being -1.

I have also been trying to use 2 Action Results as follows:

public ActionResult Profile(int ID)
    {
            ppUser viewerChoice = DB.ppUser_GetUserByPersonID(ID);
            return View(viewerChoice);
    }

    public ActionResult Profile(string ID)
    {
        ppUser viewerChoice = DB.ppUser_GetUserByVanityID(ID);
        return View(viewerChoice);
    }

But it is throwing an AmbiguousMatchException error at me when i try to call either ActionResult.

This is the routes.Maproute if it helps at all as well.

routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
            new { controller = @"[^\.]*" }, // Parameter constraints
            new string[] { typeof(MvcApplication).Namespace + ".Controllers" }
        );

Upvotes: 1

Views: 344

Answers (1)

Fabio Milheiro
Fabio Milheiro

Reputation: 8474

I think you're nearly there. Try setting a constraint for the id:

new { ID = @"\d+" }

This will guarantee that, if you try to access XXXX/User/Profile/Test, your action won't be hit because Test is not really an id.

Upvotes: 1

Related Questions