如何检查validationMessageFor是否为空?
@using (Html.BeginForm("ProfileSetting", "Home", FormMethod.Post, new { @id = "ProfileSetting" }))
{
<div class="container">
<button type="button" id="btn1" class="btn btn-primary btn-lg">Edit</button><br />
@Html.Label("Username : ")
@Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "details1 form-control", @placeholder = "Example: Bond007", Type = "text", required = "true", disabled = "true" } })
@Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger", @id = "username" })
<br />
@Html.Label("Email : ")
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "details2 form-control", Type = "email", required = "true", disabled = "true" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" ,id = "email" })
<br />
@Html.Label("Password : ")
@Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "details3 form-control", @placeholder = "Example: Bond23!", Type = "password", required = "true", disabled = "true" } })
@Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" ,id="password" })
<br />
@Html.Label("Date of Birth : ")
@Html.EditorFor(model => model.DateOfBirth, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "details4 form-control" ,@placeholder="DD-MM-YYYY",Type = "text", required = "true", disabled = "true" } })
@Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger", id = "dob" })
<br />
@Html.Label("Phone No : ")
@Html.EditorFor(model => model.PhoneNo, new { htmlAttributes = new { @class = "details5 form-control", Type = "number", @placeholder = "Phone No", required = "true", disabled = "true" } })
@Html.ValidationMessageFor(model => model.PhoneNo, "", new { @class = "text-danger", id = "phoneno" })
<br />
<label id="Successfully_Changed"></label>
<button type="button" id="btnSave" class="btn btn-primary btn-lg">Save</button>
<br />
</div>
}
在剧本中:
$('#btnSave').click(function () {
@{
if (!String.IsNullOrEmpty(@Html.ValidationMessageFor(u=>u.Username).ToString()))
{
<text>
alert($('#ProfileSetting').validate().valid());
$.post(
"/Home/EditProfile",
{
Username: $('.details1').val(),
Password: $('.details3').val(),
DateOfBirth: $('.details4').val(),
PhoneNo: $('.details5').val(),
}
);
$('#Successfully_Changed').html("Successfully Changed.");
$('#Successfully_Changed').show();
</text>
} }
});
答案 0 :(得分:-1)
在其中一条评论中,您提出的问题是:
如果没有隐藏保存按钮并将数据保存在数据库的h字段中并禁用该字段,则对控制器进行ajax调用。
如果你的目标是在进行ajax调用之前检查表单是否有效,那么就可以这样做了:
var form = $( "#formId" );
form.validate();
if (form.valid()){
// All is good so do your ajax operation.
}
valid()方法:
检查所选表格是否有效或所有选定元素是否有效。