c# - ASP.NET MVC - URL 的提取参数

标签 c# asp.net-mvc asp.net-mvc-routing

我正在尝试提取我的 URL 的参数,就像这样。

/Administration/Customer/Edit/1

摘录:1

/Administration/Product/Edit/18?allowed=true

摘录: 18?allowed=true

/Administration/Product/Create?allowed=true

摘录: ?allowed=true

有人可以帮忙吗?谢谢!

最佳答案

更新

RouteData.Values["id"] + Request.Url.Query

将匹配你所有的例子


目前还不完全清楚您要实现的目标。 MVC 通过模型绑定(bind)为您传递 URL 参数。

public class CustomerController : Controller {

  public ActionResult Edit(int id) {

    int customerId = id //the id in the URL

    return View();
  }

}


public class ProductController : Controller {

  public ActionResult Edit(int id, bool allowed) { 

    int productId = id; // the id in the URL
    bool isAllowed = allowed  // the ?allowed=true in the URL

    return View();
  }

}

在默认处理/administration/部分之前,将路由映射添加到 global.asax.cs 文件。或者您可能想查看 MVC 领域。

routes.MapRoute(
  "Admin", // Route name
  "Administration/{controller}/{action}/{id}", // URL with parameters
  new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

如果您需要的是原始 URL 数据,那么您可以使用 Controller 操作中可用的各种 URL 和 Request 属性之一

string url = Request.RawUrl;
string query= Request.Url.Query;
string isAllowed= Request.QueryString["allowed"];

听起来 Request.Url.PathAndQuery 可能就是您想要的。

如果你想访问你可以使用的原始发布数据

string isAllowed = Request.Params["allowed"];
string id = RouteData.Values["id"];

关于c# - ASP.NET MVC - URL 的提取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5003953/

相关文章:

javascript - 在 MVC 2 编辑器模板中正确注册 JavaScript 和 CSS

c# - 使用 T4MVC 自定义模型绑定(bind)器

c# - ASP.NET MVC 路由,Html.BeginForm

asp.net-mvc - ASP.NET MVC 上有免费的图表报告工具吗?

asp.net-mvc-routing - 在 .NET MVC 4.0 URL 结构中强制使用连字符

c# - EmguCV:获取两点之间直线中像素的坐标

c# - DataLoadOptions 等同于 LINQ to Entities?

c# - 在 Visual Studio 中的何处指定预处理器指令?

c# - 如何显示 List<MyObject> 中的多选列表

asp.net-mvc - 如何动态获取模型名称 mvc 4 c#4