【发布时间】:2020-09-11 09:23:03
【问题描述】:
我正在使用 if 语句,它应该在模型状态有效时执行一些操作,但显然 ModelState.IsValid 不返回 true。我曾尝试使用 ModelState.Clear() 清除之前的 ModelState,但效果不佳。
这是我的控制器
// This is the first action for which I'm using the model state
[HttpPost]
public async Task<IActionResult> Register(userModel model)
{
if (ModelState.IsValid)
{
userData lcl_userr = new userData
{
username = model.username,
password = model.password,
email = model.email
};
_context.users.Add(lcl_userr);
await _context.SaveChangesAsync();
ViewBag.Success = "Registered successfully";
ModelState.Clear();
return View();
}
return View(model);
}
// And this is the second one
[HttpPost]
public IActionResult Index(userModel model)
{
if (ModelState.IsValid)
{
var findValue = _context.users.Any(o => o.username == model.username);
var findValue2 = _context.users.Any(o => o.password == model.password);
if (findValue && findValue2)
ViewBag.Name = "Success";
}
return View(model);
}
这是表格
<form method="post" asp-action="Index" asp-controller="Portal">
<div class="text-danger"></div>
<div class="text-warning">@ViewBag.Name</div>
<div class="form-group">
<label class="mt-4 asp-for="username"">Username</label>
<input class="form-control" type="text" required="required" asp-for="username" />
<span></span>
</div>
<div class="form-group">
<label class="mt-4" asp-for="password">Password</label>
<input type="password" class="form-control" required="required" asp-for="password"/>
<span></span>
</div>
<center>Don't have an account? <a asp-controller="Portal" asp-action="Register">Register here</a>.</center>
<center><button value="login" class="btn btn-primary mt-3 w-25 mb-3 align-content-center">Login</button></center>
</form>
在动作内部调用的模型类和类成员工作正常,它从表单获取的值也工作正常,只是模型状态不起作用。
userModel 类
public class userModel
{
[Display(Name = "username")]
[Required]
public string username { get; set; }
[Required]
[Display(Name = "password")]
public string password { get; set; }
[Required]
[Display(Name = "email")]
public string email { get; set; }
}
【问题讨论】:
-
你会验证什么?您是否通过 UserModel 类上的数据注释进行验证?那么你的 UserModel 类呢? .net 完整框架还是 .net 核心?
-
我将数据从表单发送到控制器,数据将存储在 userModel 类中,然后使用 Entity Framework Core 我们将检查数据是否存在于数据库中。我正在使用 ASP.NET Core MVC,我已经编辑了问题并添加了 userModel 类。
-
你是用jquery发帖吗?
-
不,我的代码中的任何地方都没有使用 Jquery。
标签: asp.net-core model-view-controller