mvc中使用ajax

第一步骤  Model

    public class Person
    {
        [Required(ErrorMessage = "请输入姓名")]
        public string FirstName { get; set; }
        [Required(ErrorMessage = "请输入名字")]
        public string LastName { get; set; }
        [Range(18, 100, ErrorMessage = "请输入{1}到{2}之间")]
        public int age { get; set; }
        [DataType(DataType.Date)]
        public DateTime date { get; set; }
    }

 

 

第二步骤Action

     准备JsonResult

        public JsonResult Indexs()
        {
            List<Person> persons = new List<Person>();
            for (int i = 0; i < 10; i++)
            {
                Person person = new Person();
                person.FirstName = "ml";
                person.LastName = "dark";
                person.age = i;
                person.date = DateTime.Now;
                persons.Add(person);
            }

            var jsons = persons.Select(m => new { date = m.date.ToLongDateString(), age = m.age });

            return Json(jsons, JsonRequestBehavior.AllowGet);        
            //  return View(persons);       
        }

 

第三步骤view

      首先 引入JS

             <script src="@Url.Content("/Scripts/jquery.unobtrusive-ajax.js")"  type="text/javascript"></script>
      其次

            
@{
    AjaxOptions ajaxOption = new AjaxOptions {
                                              // UpdateTargetId = "updateElement" ,
                                               Url = Url.Action("indexs"),
                                               LoadingElementId="loading",
                                               LoadingElementDuration = 3000,
                                               OnSuccess = "OnSuccess"
                                             };
    }
   
@using(Ajax.BeginForm(ajaxOption))
{
        <div id="loading" style="  display:none;">加载ing</div>
        <ul id="updateElement"></ul>    
        <div>
        @Ajax.ActionLink("点击", "Indexs", ajaxOption)   
        </div>
}
 

      最后           

<script type="text/javascript">

    function OnSuccess(data) {
        var updateelement = $("#updateElement")

        for (i = 0; i < data.length; i++) {
            updateelement.append("<li>" + data[i].age + "  " + data[i].date + "</li>")
        }
    }

</script>

 

           

    注意 web.config

  <appSettings>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

 

posted @ 2012-02-28 00:33  Ry5  阅读(389)  评论(0编辑  收藏  举报