Add Value to RoutValues and keep Current Values in

2019-06-11 10:19发布

问题:

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