Add Value to RoutValues and keep Current Values in ASP.NET MVC 3

☆樱花仙子☆ 提交于 2019-12-10 11:51:06

问题


I have a view with two form one of them for declare rows per page. In post action I need my Url be the same and just add new parameter. at now I use like this:

[HttpPost]
public ActionResult Index(FormCollection collection) {

    //Calculate Row Count

    return RedirectToAction("Index", new { RC = RowCount });

   }

with this implementation my all parameters lost and just RC = rowcountnumber replaced. How can I keep parameters and just add new RC to it? what is fastest way to do it? is any performance issue here?


回答1:


check this, I am not sure is fastest or about performance issue, but worked:

RouteValueDictionary rt = new RouteValueDictionary();
    foreach(string item in Request.QueryString.AllKeys)
      rt.Add(item,    Request.QueryString.GetValues(item).FirstOrDefault());

  rt.Add("RC", RowCount);
    return RedirectToAction("Index", rt);



回答2:


Unfortunately I can't test it right now, but I suspect this would work (though it does mutate the collection parameter). And it would perform well, as it's not copying over any items from the old collection; just adding one item to it.

    [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        //Calculate Row Count
        collection.Add("RC", RowCount);
        return RedirectToAction("Index", collection);
    }



回答3:


Make the form GET not POST because the request is not changing anything on the server , so GET verb is more appropriate , and also the GET verb will pass all the form values as a query string parameters so you'll get the desired effect

to do that in the Html.BeginForm the third parameter should be FormMethod.Get



来源:https://stackoverflow.com/questions/10259463/add-value-to-routvalues-and-keep-current-values-in-asp-net-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!