将ASP.NET MVC中的form提交改为ajax提交

来源:互联网 发布:淘宝客广告海报 编辑:程序博客网 时间:2024/06/05 04:49

最近公司用MVC3做项目,本人为新手,总感觉用ASP.NET MVC自带的Ajax.BeginForm不灵活,@using (Html.BeginForm()) 产生的是form表单提交代码更是不友好,但是验证还是需要的,故而参考http://thepursuitofalife.com/asp-net-mvc-3-unobtrusive-javascript-validation-with-custom-validators/;

实战代码如下,奉上:
<script src=”@Url.Content(“~/Scripts/jquery-1.5.1.min.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>
<script type=”text/javascript”>
    $(function () {
        $(“#sbut”).click(function () {
            $(‘#interestform’).submit(function () {
                if ($(‘#interestform’).valid()) {
                    $.ajax({
                        url: ‘/mvc3/Index/’,
                        type: “Post”,
                        data: $(‘#interestform’).serialize(),
                        success: function (result) {
                            $(‘#interestcontainer’).html(result);
                        },
                        error: function (result) {
                            alert(result);
                        }
                    });
                }
                return false;
            });
           $(‘#interestform’).submit();//用来激发上面的submit绑定事件。
        })
    })
</script>
@using (Html.BeginForm(“index”, “mvc3″, FormMethod.Post, new { id = “interestform” }))
{
    <fieldset>
        <legend>UserInfo</legend>
        <div>
            @Html.LabelFor(model => model.uid)
        </div>
        <div>
            @Html.EditorFor(model => model.uid)
            @Html.ValidationMessageFor(model => model.uid)
        </div>
        <div>
            @Html.LabelFor(model => model.pwd)
        </div>
        <div>
            @Html.EditorFor(model => model.pwd)
            @Html.ValidationMessageFor(model => model.pwd)
        </div>
        <div>
            @Html.LabelFor(model => model.flag)
        </div>
        <div>
            @Html.EditorFor(model => model.flag)
            @Html.ValidationMessageFor(model => model.flag)
        </div>
        <p>
            <input type=”button” value=”Create” id=”sbut” />
        </p>
    </fieldset>
}
<div id=”interestcontainer”>
</div>
原创粉丝点击