ASP.NET MVC中RedirectToAction的用法
收藏

I want to post some questions about ASP.Net MVC. I am not familiar with web developing, But I was assigned to the web part of a project. We are doing the following: first, we create get & set properties for the person data:

public class Person
{
    public int personID {get;set;}
    public string personName {get;set;}
    public string nric {get;set;}
}

and after login, we put the data in a class Person object and we use RedirectToAction like this:

return RedirectToAction("profile","person",new { personID = Person.personID});

它正常工作,但是参数显示在URL中。我怎么能藏起来 我可以隐藏动作名称吗?请通过一些示例引导我正确的方法。

最佳答案

The parameter are shown in the URL because that is what the third parameter to RedirectToAction is - the route values.

The default route is {controller}/{action}/{id}

所以这段代码:

return RedirectToAction("profile","person",new { personID = Person.personID});

将产生以下URL /路由:

/人/个人资料/ 123

如果您想要一条更清洁的路线,例如(例如):

/人/ 123

创建一条新路线:

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

像上面一样,您的URL应该干净。

另外,您可能根本不喜欢使用ID,可以使用其他一些唯一的标识符-如昵称。

因此,URL可能像这样:

人/ rpm1984

为此,只需更改您的路线:

routes.MapRoute("PersonCleanRoute",
                    "people/{nickname}",
                    new {controller = "Person", action = "Profile"});

和你的动作方法:

public ActionResult Profile(string nickname)
{

}

和您的RedirectToAction代码:

return RedirectToAction("profile","person",new { nickname = Person.nickname});

那是你的追求吗?

    公众号
    关注公众号订阅更多技术干货!