gpt4 book ai didi

c# - 验证不适用于 ViewModel

转载 作者:行者123 更新时间:2023-11-30 15:48:49 27 4
gpt4 key购买 nike

好的,我有一个如下所示的 ViewModel:

public class UserLogin
{
[Required]
public string EmailAddress { get; set; }

[Required]
public string Password { get; set; }
}

我的 Controller 看起来像这样:

[HttpPost]
public ActionResult LogIn(UserLogin model)
{
if (!ModelState.IsValid)
{
// ...
}
}

我的观点是这样的:

<% Html.BeginForm("Join", "User", FormMethod.Post); %>
<%= Html.Hidden("ReturnUrl", Request.Url.AbsolutePath) %>

<%= Html.TextBoxFor(c => c.EmailAddress, new { id = "join-emailaddress", @class = "text", uiHintText = "Email address" })%>
<%= Html.ValidationMessageFor(c => c.EmailAddress, "*") %>

<%= Html.PasswordFor(c => c.Password, new { id = "join-password", @class = "text", uiHintText = "Password" })%>
<%= Html.ValidationMessageFor(c => c.Password, "*")%>

<%= Html.PasswordFor(c => c.PasswordConfirm, new { id = "join-password-confirm", @class = "text", uiHintText = "Password (repeat)" })%>
<%= Html.ValidationMessageFor(c => c.PasswordConfirm, "*")%>

<input type="submit" value="Sign me up!" class="submit" />
<% Html.EndForm(); %>

如果我在没有在任何字段中输入任何内容的情况下发布表单,我始终会得到“ModelState.IsValid”的“true”值。

它不应该是“false”吗,因为我已经将这些字段标记为“必填”并且没有输入任何值?

最佳答案

查看 ASP.NET MVC 的最新 RC。它包含一些针对此问题的修复。

http://haacked.com/archive/2010/02/04/aspnetmvc2-rc2.aspx

具体来说,来自发行说明:

Default validation system validates entire model
The default validation system in ASP.NET MVC 1.0 and in previews of ASP.NET MVC 2 prior to RC 2 validated only model properties that were posted to the server. In ASP.NET MVC 2 RC2, the new behavior is that all model properties are validated when the model is validated, regardless of whether a new value was posted.

有关此更改的更多信息,请参阅 Brad Wilson 博客上的以下帖子:

ASP.NET MVC 中的输入验证与模型验证
http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html

关于c# - 验证不适用于 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2256579/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com