ASP.NET MVC - 使用url参数返回View

时间:2018-03-13 15:25:59

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

我有以下代码:

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);
}

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

1 个答案:

答案 0 :(得分:0)

To&#34; forward&#34;查询字符串参数到另一个URL,您可以将它们添加为路由值。当路由遇到未定义的参数时,它会将它们添加为查询字符串参数。

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

NameValueCollectionExtensions

不幸的是,Request.QueryString参数是NameValueCollection,但路由值有一个单独的结构RouteValueDictionary,需要将查询字符串转换为。{1}}。因此,我们制作了一个简单的扩展方法,以使其更容易。

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