【问题标题】:ASP.NET MVC - return View with url parametersASP.NET MVC - 返回带有 url 参数的视图
【发布时间】:2018-03-13 15:25:59
【问题描述】:

我有以下代码:

GET方法:

public async Task<ActionResult> EditUser(string username)
{
     // something here
}

POST方法:

[HttpPost]
public async Task<ActionResult> EditUser(UserEditViewModel model)
{
    if (ModelState.IsValid)
    {
        // all right, save and redirect to user list
        return RedirectToAction("UserList");
    }

    // something wrong with model, return to form
    return View(model);
}

它工作正常,但在浏览器的 URL 中获取参数username=bla-bla-bla 丢失了。因此,用户无法复制该链接以再次打开此页面。是否可以恢复 URL 参数?如果我确实重定向,那么我会因错误而丢失模型......

【问题讨论】:

  • 不完全清楚什么不起作用。你是说如果你输入“localhost:1234/User/EditUser?username=john”,“john”就不会进入 Get 操作?
  • 我的意思是如果用户点击“刷新”然后这个页面将不会打开。或者他无法将其添加到收藏夹,复制并粘贴到其他标签,发送给朋友......
  • 所以localhost:1234/User/EditUser?username=john 会加载地址栏中没有?username=john 的页面?
  • 如果你的意思是你的方法的参数消失了,只需将它添加到你的帖子中。 public async Task&lt;ActionResult&gt; EditUser(UserEditViewModel model, string username) - 但是,请注意,这可能会使某人轻松更改用户名。如果您的意思是当您重定向到 UserList 时会丢失参数,那么您需要将这些参数添加到重定向的路由参数中。另外,请确保您的 FORM 方法 url 包含您的参数。

标签: c# asp.net-mvc asp.net-mvc-5 viewmodel asp.net-mvc-5.2


【解决方案1】:

要将查询字符串参数“转发”到另一个 URL,您可以将它们添加为路由值。当路由遇到未定义的参数时,会将其添加为查询字符串参数。

您唯一需要做的额外事情是将查询字符串参数转换回请求路由的路由值,并确保您要用作查询字符串值的参数未定义在路线中。

NameValueCollectionExtensions

不幸的是,Request.QueryString 参数是 NameValueCollection,但路由值有一个单独的结构 RouteValueDictionary,需要将查询字符串转换为该结构。所以我们做了一个简单的扩展方法来让这更容易。

public static class NameValueCollectionExtensions
{
    public static RouteValueDictionary ToRouteValueDictionary(this NameValueCollection col)
    {
        var dict = new RouteValueDictionary();
        foreach (var k in col.AllKeys)
        { 
            dict[k] = col[k];
        }  
        return dict;
    }
}

用法

[HttpPost]
public async Task<ActionResult> EditUser(UserEditViewModel model)
{
    if (ModelState.IsValid)
    {
        // all right, save and redirect to user list including
        // query string parameters.
        return RedirectToAction("UserList", this.Request.QueryString.ToRouteValueDictionary());
    }

    // something wrong with model, return to form
    return View(model);
}

假设您使用的是Default 路由:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

由于它没有定义username 路由值,将username 路由值传递给RedirectToAction 将导致它作为查询字符串参数添加到URL。

/SomeController/UserList?username=bla-bla-bla

【讨论】:

    猜你喜欢
    • 2017-06-03
    • 2010-10-06
    • 2011-02-19
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多