我对我的应用程序有部分视图我在部分视图上创建用户注册功能(不使用任何表单标签),我使用ajax-jquery& amp;来调用Controller的操作方法。将用户详细信息(模型)传递给action方法,在调用ajax方法之前,我需要在客户端验证用户详细信息。我怎么能这样做?
需要在ajax调用之前验证模型(不使用任何表单标记)。
@model MVC4Demo.Models.Student
<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 type="text/javascript">
function onClientClick() {
var obj = { FirstName: "name", City: "abc" };
$.ajax({
url: "/Home/AjaxDemo",
data: JSON.stringify(obj),
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert('success');
},
error: function () {
alert("error");
}
});
}
</script>
<div id="Main">
<label>Student</label>
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.City)
@Html.ValidationMessageFor(model => model.City)
</div>
<p>
<input type="submit" onclick="onClientClick()" value="Create" />
</p>
</div>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
答案 0 :(得分:0)
将您的模型放入表单中。后:
<script>
$(function () {
$('#myForm').unbind('submit');
$('#myForm')
.bind('submit', function () {
var form = this;
if ($("#myForm").valid()) {
$.post('/Home/AjaxDemo', $(form).serialize(), function (data) {
if (data.success) {
alert('success');
} else {
alert("error");
}
});
}
return false;
});
});
答案 1 :(得分:0)
我担心需要表格标签。还有别的,你可以预先
@Html.EnableClientValidation();
@Html.ValidationSummary(true);
到表格。