很多时候删除某个元素后,我们都希望回到原来的页面,如何实现呢?
假设在XController的index.cshtml(或aspx)中有:
- <a><hrefhref = "/area/XController/delete?id=10">
删除</a>,为了让删除后回到index页面,可以使用:
- <a><hrefhref = "/area/XController/delete?id=10&backUrl=" + @Request.Url.ToString()>
且在XController.cs中,将原来的
改为:
- [csharp] view plaincopy
- 01.<pre class="csharp" name="code">[HttpPost]
- 02.ActionResult Delete(int id)
- 03.{
- 04. try
- 05. {
- 06. ...
- 07. return RedirectToAction(...);
- 08. }
- 09. catch
- 10. {
- 11. }
- 12.}</pre><br>
- [csharp] view plaincopy
- 01.[HttpPost]
- 02.
- 03.ActionResult Delete(int id, string backUrl)
- 04.{
- 05. try
- 06. {
- 07. ...
- 08. return Redirect(backUrl);
- 09. }
- 10. catch
- 11. {
- 12. }
- 13.}
Request.Url包含了所有的地址信息(包括参数),它是一个Uri类型而非String,因此可以进行很多其他额外操作(如只要地址/服务器/查询参数等),详情可上网搜索。
没有试过"/Area/Controller/Action/id"怎么弄,应该大致相仿。
2011-08-18补充:当backUrl里边有“&”的时候(要返回的地方有多个参数),直接这样写会出错,必须:
- [html] view plaincopy
- 01.<a><hrefhrefhrefhref = "/area/XController/delete?id=10&backUrl=" + @(HttpUtility.UrlEncode(Request.Url.ToString()))>
以便对返回代码编码(把所有特殊字符全部变成%什么的,中文也一样运行)。
写多了就觉得麻烦做了个Helper:
在原来要写那些东西的地方写上Html.ReturnUrlOf(Request)就可以了(Request是View的一个属性,和Html一样随叫随到)。
但是没有最懒只有更懒,如果你和本人一样对<a>进行了封装,那么可以把接口直接封装成:
- html] view plaincopy
- 01.@Html.Link("x", "/SFC/Categories/Delete?rootID=" + root.ID + "&id=" + Model.ID, returnRequest: Request)
所有Encode 和Request问题都在 Link里边内部处理了,这个是终极做法。