Request.Form[""] 在 foreach 循环中返回 null

问题描述

在我的 .cshtml 中,我有

 <input type="text" id="snsearch" name="snsearch" style="width:180px" />

在我的 .cshtml.cs 中,我有

 var v = Request.Form["snsearch"]; //Gets the value of the textBox OK

 foreach (var x in y)

 {
   if (x.Contains(v)) //v becomes null after one iteration
   {
     //do something
   }

 }

我尝试设置一个 bool 来只捕获一次变量,但没有成功。有人对如何做到这一点有建议或其他方法吗?

解决方法

如果要获取输入的值,可以使用BindProperty在razor页面中绑定值:

cshtml:

<form method="post">
    <input type="text" id="snsearch" name="snsearch" style="width:180px" />
    <input type="submit" value="submit" />
</form>

cshtml.cs:

[BindProperty]
public string snsearch { get; set; }
public IActionResult OnPost()
        {
            foreach (var x in y)

            {
                if (x.Contains(snsearch)) 
                {

                    //do something
                }

            }
            return Page();
        }

结果(我用假数据测试): enter image description here