Ajax在MVC中的使用

Ajax在MVC中的使用更加方便,在webForm当中,当项目比较大时,有时一个页面要调用十几个ajax,我们往往会使用一堆的一般处理程序(ashx),确实很繁琐;当然你也可以使用WebService或WCF,但仅仅为了Ajax而调用WebService和WCF,感觉像是杀鸡用牛刀!

而在MVC中,调用Ajax就跟调用普通方法一样,主要使用以下两种方式调用

前端代码:

    <%using (Ajax.BeginForm("Create", null, new AjaxOptions { HttpMethod = "POST" }, new { id="form1"}))
      { %>
     <%-- <%using (Html.BeginForm("Create", "Home", FormMethod.Post, new { id="form1"}))
        { %> 这是没有使用ajax的form--%>
      <%:Html.Label("Name")%>
      <%:Html.TextBox("Name")%>
      <%:Html.ValidationMessage("Name")%><br />
      <%:Html.Label("Password")%>
      <%:Html.TextBox("Password")%>
      <%:Html.ValidationMessage("Password")%><br />
      <%:Html.Label("Password2")%>
      <%:Html.TextBox("Password2")%>
      <%:Html.ValidationMessage("Password2")%><br />
      <%:Html.Label("Email")%>
      <%:Html.TextBox("Email")%>
      <%:Html.ValidationMessage("Email")%><br />
      <input type="submit" value="注 册" id="submit"/>
        <%} %>
    </div>
    <input type="button" value="添加" id="add"/><%--jquery提交--%>

 

Model的代码

public class RegisterUserModel
    {
        [Display( Name="用户名")]
        [Required(ErrorMessage="用户名不能为空")]
        //[Remote("ValidateName","Home",ErrorMessage="用户名长度必须为4-12位")]
        [Remote("ValidateUserName","Home",ErrorMessage="该用户名已经被注册")]//使用ajax方法进行验证
        public string Name { get; set; }

        [Display(Name = "密码")]
        [Required(ErrorMessage = "密码不能为空")]
        public string Password { get; set; }

        [Display(Name = "确认密码")]
        [Compare("Password",ErrorMessage="确认密码与新密码不一致")]
        public string Password2 { get; set; }

        [Display(Name = "邮箱")]
        [Required(ErrorMessage = "邮箱不能为空")]
        [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",ErrorMessage="邮箱格式不正确")]
        public string Email { get; set; }
    }

Controller

        [HttpPost]
        public ActionResult Create(RegisterUserModel collection)
        {
            if (ModelState.IsValid)
            {
                Users user = new Users
                {
                    UserName = collection.Name,
                    Password = collection.Password,
                    Email = collection.Email
                };
                context.AddToUsers(user);
                context.SaveChanges();
                return Json("ok");
            }
            return Json("fail");
        }

 

一.Ajax.BeginForm(),这是调用微软已经帮我们封装好了的方法

   实现如前端代码所示:

    <%using (Ajax.BeginForm("Create", null, new AjaxOptions { HttpMethod = "POST" }, new { id="form1"}))
      { %>

调用的action为Create,使用Post方式;非常方便!

二,使用jquery的ajax方法,个人还是习惯于使用jquery.

   jquery代码如下

    $(function () {
                $("#add").click(function () {
                    $.post("Create", $("#form1").serialize(), function (data, status) {
                        if (status == "success") {
                            alert(data);
                        }
                    });
                });
    });

 记得别忘了引用:

<script src="<%: Url.Content("~/Scripts/jquery-1.4.4.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>

posted @ 2012-07-09 14:46  Jeff.Zhong  阅读(6589)  评论(1编辑  收藏  举报