.cshtml 中 Request.Form 的问题

Trouble with Request.Form inside .cshtml

Trying to create a page that will have a drop down selector with three image names and when an image name is selected and you hit submit it will then display that image on the page.

我在这里找到了一个例子(似乎已经过时):https://docs.microsoft.com/en-us/aspnet/web-pages/overview/ui-layouts-and-themes/9-working-with-images

有:if(请求["photoChoice"] != null)

在某处读到更正为 Request.Form

@{ var imagePath = "";
    if (Request.Form["photoChoice"] != null)
        {
            imagePath = @"images\" + Request.Form["photoChoice"];
        }
}


<form method="post" action="">
    <div>
        I want to see:
        <select name="photoChoice">
            <option value="Photo1.jpg">Photo 1</option>
            <option value="Photo2.jpg">Photo 2</option>
            <option value="Photo3.jpg">Photo 3</option>
        </select>
        &nbsp;
        <input type="submit" value="Submit" />
    </div>
    <div style="padding:10px;">
        @if (imagePath != "")
        {
            <img src="@imagePath" alt="Sample Image" width="300" />
        }
    </div>
</form>

我遇到的第一个错误是: “运算符 '!=' 在 'StringValues' 和 'null' 类型的操作数上不明确”

在 if 语句的 Request 开头添加 (object)

@{ var imagePath = "";
    if ((object)Request.Form["photoChoice"] != null)
        {
            imagePath = @"images\" + Request.Form["photoChoice"];
        }

现在我在尝试编译站点时遇到另一个错误 "InvalidOperationException: Incorrect Content-Type"。它确实引用了 If 代码行

The link you refer to is used in asp.net, not in core.

The main reason for the error is that you put the request.Form in the wrong place. Your current requirements should put the code into the OnPost method in the code behind.

这个功能在内核中有多种实现方式,但需要在后面代码中的post方法中触发。

请参考this

最简单的方法就是在代码后面bind fields。详情请参考以下

Page.cs:

public class ShowImagesModel : PageModel
    {
        [BindProperty]
        public string imagePath { get; set; }
        [BindProperty]
        public string photoChoice { get; set; }
        public void OnGet()
        {
            imagePath = "";

        }
        public void OnPost()
        {
            if (!string.IsNullOrEmpty(photoChoice))
            {
                imagePath = @"images\" + photoChoice;
            }
        }

    }

查看:

@page
@model WebApplication1_razor_page.ShowImagesModel
@{
    ViewData["Title"] = "ShowImages";
    Layout = "~/Pages/Shared/_Layout.cshtml"; 
} 
<h1>ShowImages</h1>

<form method="post" action="">
    <div>
        I want to see:
        <select asp-for="photoChoice" >
            <option value="Photo1.jpg">Photo 1</option>
            <option value="Photo2.jpg">Photo 2</option>
            <option value="Photo3.jpg">Photo 3</option>
        </select>
        &nbsp;
        <input type="submit" value="Submit" />
    </div>
    <div style="padding:10px;">
        @if (Model.imagePath != "")
        {
            <img src="@Model.imagePath" alt="Sample Image" width="300" />
        }
    </div>
</form>

结果如下: