asp.net-mvc - 检查 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)
,因为它显示了以下内容:
所以我然后删除了.Input
from 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
是如果用户在文本框中输入内容并点击按钮,则将用户重定向到另一个页面 ( )。如果用户没有在文本框中输入任何内容并且仍然点击按钮进入下一页,那么它需要抛出异常。
我做错了什么吗?任何建议将不胜感激!
解决方案
你快到了,但是在视图和控制器端需要做一些改变来让它工作。
你需要有类型为提交的输入按钮
@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");
}
推荐阅读
- python - 即使满足包要求,也解决anaconda enviroment.yml中的ResolvePackageNotFound错误?
- python - XML/KML 格式不正确
- python - 如何将终端输出显示到 PyQt 中的文本框
- http - 从 net/http.Request.RemoteAddr 获取 IP 地址的最简洁方法是什么
- solr - solrj 是否支持使用 _nest_path_ 字段索引嵌套文档?
- citations - 将引文标签更改为每位作者仅包含一到两个字母
- rust - 如何在线程中借值而不是移动
- opencv - Visual Studio 2017 自动链接依赖的依赖
- tfs - 是否可以在 TFS 关闭时编辑代码
- python - 如何在 Google Colab 中进行文本到语音的转换?