asp.net-mvc 使用剃刀进行表单验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12736102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
form validation with razor
提问by sagesky36
I have the following in my .net mvc razor form and I'm clicking on the submit button, but it's not being validated by the validation in the js. I debugged it in Firefox and instead, goes right to the form method and no validation comes out on the form to stop the form submission.
我的 .net mvc razor 表单中有以下内容,我点击了提交按钮,但它没有通过 js 中的验证进行验证。我在 Firefox 中调试了它,而是直接转到表单方法,并且表单上没有验证来停止表单提交。
the HTML output of the model.LoanId is simply LoanId.
model.LoanId 的 HTML 输出就是 LoanId。
How can I properly validate the form????
如何正确验证表单????
What am I doing wrong?
我究竟做错了什么?
HTML
HTML
@using (Html.BeginForm("Refresh", "Home", FormMethod.Post, new { id = "frmTemps" }))
<tr>
<td>
@Html.LabelFor(model => model.LoanId)
@Html.TextBoxFor(model => model.LoanId)
<td colspan="3">
<input type="submit" id="btnRefresh" value='Refresh' />
</td>
</tr>
js
$("#frmTemps").validate({
event: "submit",
rules: {
LoanID: {
required: true
}
},
messages: {
LoanID: {
required: ' Please enter a Loan ID. '
}
}
});
I also tried it with non-model data below and got the same thing.
@Html.Label("loanid:", "LoanID")
@Html.TextBox("loanID")
Here is the html I'm trying to validate:
<td>@Html.LabelFor(model => model.LoanType)
@Html.TextBox("SBA", "SBA")
@Html.ValidationMessageFor(model => model.LoanType)
@*@Html.TextBoxFor(model => model.LoanType)*@
</td>
<td>
<label for="ddlDept">Department:</label>
@(Html.Kendo().DropDownListFor(model => model.SelectedDeptText)
.Name("ddlDept")
.DataTextField("DepartmentName")
.DataValueField("DepartmentID")
.Events(e => e.Change("Refresh"))
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetDepartments", "Home");
});
})
)
@Html.ValidationMessageFor(model => model.SelectedDeptText)
View Model
查看模型
public class ViewModelTemplate_Guarantors
{
public int SelectedTemplateId { get; set; }
public IEnumerable<PDFTemplate> Templates { get; set; }
public int SelectedGuarantorId { get; set; }
public IEnumerable<tGuarantor> Guarantors { get; set; }
public string LoanId { get; set; }
public string SelectedDeptText { get; set; }
public string LoanType { get; set; }
public bool ShowTemps { get; set; }
public string Error { get; set; }
public string ErrorT { get; set; }
public string ErrorG { get; set; }
public bool ShowGeneratePDFBtn { get; set; }
}
_Layout.cshtml
_Layout.cshtml
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/modernizr-2.5.3.js"></script>
<script src="@Url.Content("~/Scripts/kendo/2012.2.913/kendo.all.min.js")"></script>
<script src="@Url.Content("~/Scripts/kendo/2012.2.913/kendo.aspnetmvc.min.js")"></script>
Validation class
验证类
namespace PDFService03Validation.Validations
{
[MetadataType(typeof(PDFService03_Validation))]
public partial class PDFService03
{
}
public partial class PDFService03_Validation
{
public class PDFService03
{
[Required(ErrorMessage = "Loan ID Required")]
[DataType(DataType.Text)]
public string LoanID { get; set; }
[Required(ErrorMessage = "Loan Type Required")]
[DataType(DataType.Text)]
public string LoanType { get; set; }
[Required(ErrorMessage = "Department Name Required")]
[DataType(DataType.Text)]
public string SelectedDeptText { get; set; }
}
}
}
Index method
索引法
public ActionResult Index(ViewModelTemplate_Guarantors model)
{
ViewBag.Error = "";
model.ShowGeneratePDFBtn = false;
return View();
}
Index.cshtml- still thinks the object is not set. When debugging, I go into my Controller, sets the variable in the model, then, comes back here. Please help... I don't know what I'm doing incorrectly here. I think I've followed everything as needed.
Index.cshtml- 仍然认为对象没有设置。调试时,我进入我的控制器,在模型中设置变量,然后返回这里。请帮助...我不知道我在这里做错了什么。我想我已经根据需要遵循了一切。
Sorry to bug you again, but I'm almost there....
很抱歉再次打扰您,但我快到了....
I did as you said, but still am not getting any validation errors....
我按照你说的做了,但仍然没有收到任何验证错误......
Below, is the html markup that is produced by my View. You can see the scripts I'm using at the top and you can also see the validation in the span tags. What am I missing??? I'm also going to show you the ViewModel I edited. thanks so much ahead of time...
下面是我的视图生成的 html 标记。您可以在顶部看到我正在使用的脚本,还可以在 span 标签中看到验证。我错过了什么???我还将向您展示我编辑的 ViewModel。非常感谢提前...
ViewModel
视图模型
namespace PDFConverterModel.ViewModels
{
[MetadataType(typeof(ViewModelTemplate_Guarantors_Validation))]
public partial class ViewModelTemplate_GuarantorsValidation
{
}
public partial class ViewModelTemplate_Guarantors_Validation
{
public class ViewModelTemplate_Guarantors
{
[Required(ErrorMessage = "Loan ID Required")]
[DataType(DataType.Text)]
public string LoanID { get; set; }
[Required(ErrorMessage = "Loan Type Required")]
[DataType(DataType.Text)]
public string LoanType { get; set; }
[Required(ErrorMessage = "Department Name Required")]
[DataType(DataType.Text)]
public string SelectedDeptText { get; set; }
}
}
public class ViewModelTemplate_Guarantors
{
public int SelectedTemplateId { get; set; }
public IEnumerable<PDFTemplate> Templates { get; set; }
public int SelectedGuarantorId { get; set; }
public IEnumerable<tGuarantor> Guarantors { get; set; }
public string LoanId { get; set; }
public string SelectedDeptText { get; set; }
public string LoanType { get; set; }
public bool ShowTemps { get; set; }
public string Error { get; set; }
public string ErrorT { get; set; }
public string ErrorG { get; set; }
public bool ShowGeneratePDFBtn { get; set; }
}
}
Page output:
页面输出:
<!DOCTYPE html>
<html>
<head>
<title>BHG :: PDF Generator</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="/Content/kendo/2012.2.913/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="/Content/kendo/2012.2.913/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="/Content/kendo/2012.2.913/kendo.blueopal.min.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="/Scripts/modernizr-2.5.3.js"></script>
<script src="/Scripts/kendo/2012.2.913/kendo.all.min.js"></script>
<script src="/Scripts/kendo/2012.2.913/kendo.aspnetmvc.min.js"></script>
</head>
<body>
<div class="page">
<header>
<div id="title">
<h1>BHG :: PDF Generator</h1>
</div>
</header>
<section id="main">
<h2></h2>
<div>
<table style="width: 1000px">
<tr>
<td colspan="5">
<img alt="BHG Logo" src="/Images/logo.gif" />
</td>
</tr>
<form action="/Home/Refresh" id="frmTemps" method="post"> <tr>
<td>
<label for="LoanId">LoanId</label>
<input id="LoanId" name="LoanId" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="LoanId" data-valmsg-replace="true"></span>
<td colspan="3">
<input type="submit" id="btnRefresh" value='Refresh' />
</td>
</tr>
<tr>
<td><label for="LoanType">LoanType</label>
<input id="SBA" name="SBA" type="text" value="SBA" />
<span class="field-validation-valid" data-valmsg-for="LoanType" data-valmsg-replace="true"></span>
</td>
<td>
<label for="ddlDept">Department:</label>
<input id="ddlDept" name="ddlDept" type="text" /><script>
jQuery(function(){jQuery("#ddlDept").kendoDropDownList({"change":Refresh,"dataSource":{"transport":{"read":{"url":"/Home/GetDepartments"}},"schema":{"errors":"Errors"}},"dataTextField":"DepartmentName","dataValueField":"DepartmentID"});});
</script>
<span class="field-validation-valid" data-valmsg-for="SelectedDeptText" data-valmsg-replace="true"></span>
</td>
</tr>
</form>
</table>
</div>
<script type="text/javascript">
$('btnRefresh').on('click', '#btnRefresh', function () {
Refresh();
});
function Refresh() {
var LoanID = $("#LoanID").val();
if (LoanID != "") {
document.forms["frmTemps"].submit();
}
}
</script>
</section>
<footer>
</footer>
</div>
</body>
</html>
回答by Leniel Maccaferri
Oh... I see why this is happening. You're forgetting this:
哦...我明白为什么会这样了。你忘记了这一点:
@Html.ValidationMessageFor(model => model.LoanId)
If you don't put the ValidationMessageFor, the unobtrusive validation won't know that this model property needs to be validated before the form submission.
如果不放置ValidationMessageFor,不显眼的验证将不知道在表单提交之前需要验证此模型属性。
So you must have this:
所以你必须有这个:
@Html.LabelFor(model => model.LoanId)
@Html.TextBoxFor(model => model.LoanId)
@Html.ValidationMessageFor(model => model.LoanId)
Don't forget to put some data annotation in your LoanIdproperty first...
不要忘记先在您的LoanId属性中添加一些数据注释...
For more on this, look here: Validation with the Data Annotation Validators (C#)
有关更多信息,请查看此处:使用数据注释验证器 (C#) 进行验证
EDIT
编辑
After you provided more code to the question I could see why the validation errors are not showing.
在您为问题提供更多代码后,我可以看到为什么没有显示验证错误。
This happens because you're actually passing your custom ViewModel ViewModelTemplate_Guarantorsto the view. As you can see, your view model has no data annotations. The data annotations you provided in the metadata class PDFService03_Validationwill only take effect if you pass an object of type PDFService03to the view. So to solve the problem you'll have to duplicate your data annotations in your ViewModelTemplate_Guarantorsview model object. This is code repetition and is terrible ugly but is how it works.
发生这种情况是因为您实际上是将自定义 ViewModel 传递ViewModelTemplate_Guarantors给视图。如您所见,您的视图模型没有数据注释。您在元数据类中提供的数据注释PDFService03_Validation只有在您将类型的对象传递PDFService03给视图时才会生效。因此,要解决该问题,您必须在ViewModelTemplate_Guarantors视图模型对象中复制数据注释。这是代码重复,非常丑陋,但它是如何工作的。
回答by Anirudh Agarwal
- jquery-1.7.1.min.j
- kendo.web.min.js
- kendo.aspnetmvc.min.js
- kendo.validator.min.js
- kendo.dataviz.min.js
- jquery-1.7.1.min.j
- 剑道.web.min.js
- 剑道.aspnetmvc.min.js
- kendo.validator.min.js
- 剑道.dataviz.min.js
These 5 files are necessary for the validation to work. I have seen you have added few of these add all these and try. I also faced this problem but this have solved the problem.
这 5 个文件是验证工作所必需的。我已经看到您添加了其中的一些添加所有这些并尝试。我也遇到了这个问题,但这已经解决了问题。
also check you web config for this:
还要检查您的网络配置:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
This is also required. Let me no f it works.
这也是必需的。让我没有它的工作原理。

