Question

Currently I have a Member controller which has 2 views, Index and Details, I would like to pass a string such as UserName to the view Details, which in turn displays the results of the query.

public ActionResult Details(string u)
{
    if (u == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    AspNetUser user = db.AspNetUsers.Find(u);
    if (user == null)
    {
        return HttpNotFound();
    }
    return View(user);
}

In the Index view I am using a link like so:

@Html.ActionLink(item.UserName, "Details", new { u = item.UserName })

When I click a link such as:

http://localhost:11508/Member/Details?u=test7

I get the message:

HTTP Error 404.0 - Not Found

What am I doing wrong?

Was it helpful?

Solution

You could try adding the next line in RouteConfig.cs in RegisterRoutes method:

routes.MapRoute(
        name: "Details",
        url: "{controller}/{action}/{u}",
        defaults: new { 
            controller = "Member", 
            action = "Details", 
            u = UrlParameter.Optional }
    );

OTHER TIPS

The method you are calling has the following signature:

protected internal virtual ViewResult View(string viewName, string masterName, object model)

With the above method, C# thinks that the viewname is the username, which I assume is not correct. By using named parameters you can force a string as a model:

return View(viewName: "Details", model: item.UserName);

this way C# will use the correct method.

I'm not really sure what the other answers are getting at. Your Html.ActionLink is fine. In your controller you have

AspNetUser user = db.AspNetUsers.Find(u);
if (user == null)
{
    return HttpNotFound();
}

put a breakpoint and check if user == null is true. That's most likely your issue.

Providing you use the default routes for this, you can change your controller method to use [Bind(Prefix="id")].

public ActionResult Details([Bind(Prefix="id")]string u)
{
    if (u == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    AspNetUser user = db.AspNetUsers.Find(u);
    if (user == null)
    {
        return HttpNotFound();
    }
    return View(user);
}

I think the method you use to find the user takes the userId though, and you send in the username. So that might be an issue as well!

Edit: example for finding the user by username

db.AspNetUsers.FirstOrDefault(usr=>usr.UserName == u)

The [Bind] prefix is only for making the url follow the normal syntax.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top