0

在查看了很多问题和 Internet 数据后,我解决了我的一个问题,即正确地从 MVC3 应用程序获取 URL 参数。问题是编码没有错误,但在路由方面(我对路由不太擅长......)。这是当前的问题。

http://localhost:51561/Report/Details/1

这是我的应用程序呈现报告详细信息的方式,这很好。但是当它这样做时,我无法从 URL 参数中获取值,就像这样

Request.QueryString["id"]

但是,当我手动输入 URL 时http://localhost:51561/Report/Details?id=1,它可以工作......事情是我喜欢第一个 URL 类型,但我不知道如何从中获取参数......

请帮忙...

更新:

我的控制器操作:

public ViewResult Details(int id)
    {
        Report report = db.Reports.Find(id);
        ViewBag.TestID = Request.QueryString["id"].ToString();
        return View(report);
    }

    public ActionResult Show(int id)
    {
        Report report = db.Reports.Find(id);
        var imageData = report.Image;
        return (File(imageData, "image/jpg"));
    }

我的观点:

<div class="display-label">Picture</div>
<div class="display-field">
   <img alt="image" src="<%=Url.Action("Show", "Report", new { id = ViewBag.TestID })%>" width="200px" />
</div>
4

2 回答 2

1

你不应该Request.QueryString["id"]在 MVC中使用

只需id在您的操作中添加参数ReportController.Details

public ActionResult Details (int id)

以上假设您在 Global.asax 中有一个默认路由设置:

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
    );
于 2012-06-25T16:32:16.360 回答
1

首先,你不应该Request.QueryString在你的应用程序中使用。除此之外,在第一个 URL 中,您没有查询字符串,因此您无法访问它(另请阅读msdn 上的这篇文章Request.QueryStringabout )。

我还想建议您阅读 ASP.NET MVC3 的基本教程,可在此处找到。像你的问题这样的许多事情都在那里得到了彻底的解释。

现在回答您的问题,在您的第一个 URL 示例中, 1URL 中的 是您的操作(详细信息操作)的参数。您必须将此参数添加到您的方法(操作)中:

public ActionResult Details(int id)

更新:你显然有正确的行动(方法)声明。现在,您可以只使用参数id。因此,Request.QueryString["id"]只需通过变量 (parameter)更改id

public ViewResult Details(int id)
{
    Report report = db.Reports.Find(id);
    ViewBag.TestID = id;
    return View(report);
}

没有必要申请ToString()id,你不应该在不需要的时候申请(你可能在其他地方需要它,稍后左右)。只需将其ViewBag作为原始类型放入即可。

你的Show()方法很好:)。您现在拥有id所需的参数。(尽量避免使用过多的括号,这会使它看起来很乱,现在又很清楚。)

public ActionResult Show(int id)
{
    Report report = db.Reports.Find(id);
    var imageData = report.Image;
    return File(imageData, "image/jpg");
}
于 2012-06-25T16:36:20.483 回答