首页 > 解决方案 > 检查 Html Input 文本字段是否有值

问题描述

在我的 asp.net Web 应用程序(mvc)上,我想检查用户在单击按钮时是否在文本字段中输入了一个值,以及是否要重定向到下一页。如果不是,则抛出异常。我查看了如何执行此操作,并尝试使用它,Html.BeginForm()但由于某种原因,当我将文本框留空并点击提交按钮时,它仍然会输入我的条件语句。

原始代码:

第二控制器:

        [HttpPost]
        public IActionResult Insert(String inputF)
        {
          
            if (inputF == null)
            {
                throw new Exception("You did not type anything in the textfield!!!!");
            }
            else
            {
                return RedirectToAction("FinalIndex", "Final");
            }
        }

我希望它抛出异常但不停止程序继续运行,就像它在 UI 中向用户返回消息但仍记录所产生的异常。

更新代码:

我的第二控制器:

    [HttpPost]
    public IActionResult Insert(String inputF)
    {
      
        if (!ModelState.IsValid || String.IsNullOrWhiteSpace(inputF.Input))
        {
            return View(inputF);
        }
        else
        {
            return RedirectToAction("FinalIndex", "Final");
        }
    }

它不允许我这样做String.IsNullOrWhiteSpace(inputF.Input),因为它显示了以下内容:

在此处输入图像描述

所以我然后删除了.Inputfrom inputF.Input,它仍然给了我下图中未处理的消息

我的观点:

@using CustomerSimulatorApp.Models
@model TextInput 

<h2>Second page</h2>



@using (Html.BeginForm("Insert", "Second", FormMethod.Post))
{
    @Html.TextBoxFor(r => r.Input);

    <input id="Button" type="submit" value="button" />

} 

我的模型:

namespace CustomerSimulatorApp.Models
{
    public class TextInput
    {
        [Required, MinLength(1)] 
        public String Input { get; set; }
    }
}

当我将文本框留空并点击按钮时,它会返回如下所示:

在此处输入图像描述

不确定,如果这正是应该发生的事情,或者是否应该抛出一个实际的异常。此外,当我在框中键入一个字符并点击按钮时,它仍然允许我继续进行重定向,并且无论[Required MinLength(2)]我的属性如何都不会引发异常。

所以我的目标FinalIndex是如果用户在文本框中输入内容并点击按钮,则将用户重定向到另一个页面 ( )。如果用户没有在文本框中输入任何内容并且仍然点击按钮进入下一页,那么它需要抛出异常。

我做错了什么吗?任何建议将不胜感激!

标签: asp.net-mvc

解决方案


你快到了,但是在视图和控制器端需要做一些改变来让它工作。

  • 你需要有类型为提交的输入按钮

    @using (Html.BeginForm("Insert", "Second", FormMethod.Post))
    {
        @Html.TextBoxFor(r => r.Input);
    
        <input id="Button" type="submit" value="button" />
    }
    

并且在控制器操作代码中应该是这样的:

// this if checks if input textbox value is not present load back page with error
if (!ModelState.IsValid || String.IsNullOrWhiteSpace(inputF.Input))
{
    return View(inputF);
}
else
{
     // there was value in input redirect to Final controller action
     return RedirectToAction("FinalIndex","Final");
}

推荐阅读