0

我对我的应用程序有一个部分视图我正在部分视图上创建用户注册功能(不使用任何表单标记),我正在使用 ajax-jquery 调用控制器的操作方法并将用户详细信息(模型)传递给操作方法,然后再调用 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>
4

2 回答 2

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;
        });
});

于 2013-03-26T21:18:02.937 回答
0

恐怕需要表单标签。还有别的东西,你可以预先

@Html.EnableClientValidation();
@Html.ValidationSummary(true);

到表格。

于 2013-03-27T03:23:30.330 回答