在MVC3中,控制器如何知道非侵入性验证的结果?
我正在使用 C#
、MVC3
和 VS2010
我注意到,即使验证结果为 false,控制器方法仍然会被执行。这使得验证在服务器端毫无用处。除非有办法得到结果。
---- 编辑 -----
这是我的使用方法。做得正确吗?至少会显示验证消息,并且文本框会变成红色。
型号:
public class CategoriaModel
{
[Required(ErrorMessage="Nome é obrigatório!")]
[StringLength(10, ErrorMessage = "First Name max length is 10")]
public string Nome { get; set; }
}
视图:
@Html.ValidationSummary(true)
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
@using (Html.BeginForm("Salvar", "Test", FormMethod.Post))
{
@Html.LabelFor(m => m.Nome)
@Html.EditorFor(m => m.Nome)
@Html.ValidationMessageFor(m=>m.Nome)
<input type="submit" value="Salvar" />
}
控制器:
public ActionResult Salvar(CategoriaModel catModel)
{
ViewBag.StatusMessage = "Ok!";
return View("Index");
}
I'm using C#
, MVC3
and VS2010
I noticed that even though the valdiation results to false, the controller method still gets executed. This makes the validation useless on the server-side. Unless there is a way to get the result.
---- EDITS -----
Here is how i'm using it. Is it done properly? At least the validation messages show up, and the textbox turns red.
Model:
public class CategoriaModel
{
[Required(ErrorMessage="Nome é obrigatório!")]
[StringLength(10, ErrorMessage = "First Name max length is 10")]
public string Nome { get; set; }
}
View:
@Html.ValidationSummary(true)
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" type="text/javascript"></script>
@using (Html.BeginForm("Salvar", "Test", FormMethod.Post))
{
@Html.LabelFor(m => m.Nome)
@Html.EditorFor(m => m.Nome)
@Html.ValidationMessageFor(m=>m.Nome)
<input type="submit" value="Salvar" />
}
Controller:
public ActionResult Salvar(CategoriaModel catModel)
{
ViewBag.StatusMessage = "Ok!";
return View("Index");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
测试
ModelState.IsValid
属性,但是如果客户端验证失败,则不应调用操作。检查您是否确实正在验证所有模型属性。testing
ModelState.IsValid
property, however if client side validation fails the Action should not be called. Check if you're actually validating all your Model properties.