繁体   English   中英

“当前上下文中不存在名称‘请求’”

[英]"The name 'Request' does not exist in the current context"

编辑:我现在已将Request更改为Context.Request并且现在收到与此帖子标题不同的错误: Cannot apply indexing with [] to an expression of type 'HttpRequest'

因此,我正在尝试向 ASP.Net 介绍自己,并按照此处提供的在线教程进行操作: https : //www.w3schools.com/asp/webpages_forms.asp (“显示图像”部分)。 我试图在 MVC 风格的布局中实现这一点。 该结构的起始模板是运行dotnet new -t web时生成的模板的修改版本。

在我的 Pictures.cshtml 文件中,我有以下内容:

@{
    ViewData["Title"] = "Pictures";

    var imagePath="";
    if (Request["Choice"] != null) 
    {
       imagePath="images/" + Request["Choice"];
    }
}

<h2>Pictures</h2>

<form method="post" action="">
    I want to see:
    <select name="Choice">
    <option value="Photo1.jpg">Photo 1</option>
    <option value="Photo2.jpg">Photo 2</option>
    <option value="Photo3.jpg">Photo 3</option>
    </select>
    <input type="submit" value="Submit" />
    @if (imagePath != "")
    {
        <p>
        <img src="@imagePath" alt="Sample" />
        </p>
    }
</form>

这是从 MainController.cs 调用的,如下所示:

using Microsoft.AspNetCore.Mvc;

namespace WebApp.Controllers
{
    public class MainController : Controller
    {
        public IActionResult Pictures()
        {
             return View();
        }
    }
}

还有一个 _ViewStart.cshtml 引用了 _Layout.cshtml。

运行它时,我被重定向到我的错误页面,并且终端给出错误The name 'Request' does not exist in the current context

有人可以帮助我指出我缺少什么或我做错了什么的正确方向吗? 为什么本教程示例在我的项目上下文中不起作用?

干杯:)

我在 Core 2.1 中遇到了同样的错误。 我发现如果你把它放在ViewDataStyles部分,它很难调试(或者只是有点奇怪)。 否则,对于特定参数,它应该像这样工作:

@Context.Request.Query["Choice"]

对于您的代码,我只会请求一次该值并将其分配给一个变量,然后查看它是否为空。 然后,从您的变量创建路径:

var choice = @Context.Request.Query["Choice"];
var imagePath="";
if (!String.IsNullOrEmpty(choice)){
   imagePath="images/" + choice;
}

作为奖励,您还可以通过以下方式获取包含所有名称和值的整个查询字符串(以防您想解析它或其他):

@Context.Request.QueryString

我在 ASP Core 5.0 中使用它:

ViewContext.HttpContext.Request.Query["Choice"]

JS中的例子:

if (getParameterByName("error") != null) {
   window.location.href = "@Url.Action("Login", "Home" , new { error = ViewContext.HttpContext.Request.Query["Choice"] })";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM