如何在 ASP.NET MVC 中保留查询字符串值?
在 ASP.NET MVC 中保存查询字符串值的好方法是什么?
如果我有一个网址: /questions?page=2&sort=newest&items=50&showcomments=1&search=abcd
在分页链接上,我想在所有链接中保留这些查询字符串值,以便当用户单击“下一页”时它们仍然存在例如(在这种情况下,页面值会改变,但其余部分保持不变)
我可以想到两种方法来做到这一点:
- 在视图中请求.Querystring并将值添加到链接
- 将每个查询字符串值从控制器传回使用 ViewData 进入视图
一个比另一个更好吗? 这些是唯一的选择还是有更好的方法来做到这一点?
What is a good way to persist querystring values in asp.net mvc?
If I have a url:
/questions?page=2&sort=newest&items=50&showcomments=1&search=abcd
On paging links I want to keep those querystring values in all the links so they persist when the user clicks on the "next page" for example (in this case the page value would change, but the rest would stay the same)
I can think of 2 ways to do this:
- Request.Querystring in the View and add the values to the links
- Pass each querystring value from the Controller back into the View using ViewData
Is one better than the other? Are those the only options or is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我为此使用了扩展方法:
i use a extension method for that:
我将在视图中处理 QueryString(您的选项#1),而不是从控制器传递它。 这种方法使视图更加独立,允许您将其转换为视图控件并在不同的视图中重复使用它。
注意:直接在视图中访问 QueryString 似乎违反了模型和视图分离的设计原则,但实际上这些数据是与视图相关的导航问题,而不是模型的真正一部分。
I would process the QueryString in the view (your option #1), instead of passing it in from the controller. This approach makes the view more self-contained, allowing you to convert it into a view control and re-use it across different views.
Note: Accessing the QueryString directly in the view may seem like a violation of the design principle of separating the Model and View, but in reality this data is a navigational concern which is related to the view, not really part of the model.
我只是将值保留在会话中,这样分页链接只需要具有;
我不使用 QueryString 的原因之一是我不希望用户看到我传递给程序的值。 这使得他们很容易进入地址栏并开始更改值以“看看会发生什么”。 使用此代码,他们所能做的就是更改页码。
I would just keep the values in the Session that way the paging links only need to have;
The one reason why I would not us the QueryString is because I don't want the user to see the values that I am passing to the program. It makes it way too easy for them to go into the address bar and start changing the values to 'see what happens'. With this code all they could do is change the page number.
这是我在 Asp.Net Core 中完成的方法,首先将查询字符串参数分配给控制器中的 ViewBags:
然后将值传递给链接,如下所示:
请注意,每个链接都保留其自己的实际值并传递其余的路由值通过我们传递给 ViewBag 的内容。
Here's how I done it in Asp.Net Core, first assign the query string parameters to ViewBags in your controller:
Then pass the values to your links like so:
Note that every link keep its own actual value and pass the rest of the route values through what we passed to ViewBag.