MVC非唐突Ajax的使用

前端之家收集整理的这篇文章主要介绍了MVC非唐突Ajax的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

MVC包含了对非唐突Ajax的支持,非唐突Ajax的作用可以让你不必再HTML代码里面嵌套javascript代码.非唐突Ajax也是需要JQUERY支持的.

先说一下AjaxOptions对象(MSDN):表示用于在 MVC 应用程序中运行 AJAX 脚本的选项设置。我们主要是通过配置该类对象的属性值来代替写js代码,比如"回调函数"

AjaxOptions的属性都是可选的,如下图:


使用方法:

1) 根目录配置文件设置

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

2) 在视图中,对应的js的引入

    <script src="~/Scripts/jquery-1.8.2.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

3)在视图中配置AjaxOptions对象
@{
    AjaxOptions ajaxOpts = new AjaxOptions
    {
        UpdateTargetId = "tabledata"
    };
}

<!DOCTYPE html>
<html>


好了,看一个例子( 下载)吧,根据名称,筛选数据

先看控制器:

    public class AppointmentController : Controller
    {
        //自己建的数据源
        IEnumerable<Appointment> data = new[] {
                        new Appointment { ClientName = "Joe",Date = DateTime.Parse("1/1/2012")},new Appointment { ClientName = "Joe",Date = DateTime.Parse("2/1/2012")},Date = DateTime.Parse("3/1/2012")},new Appointment { ClientName = "Jane",Date = DateTime.Parse("1/20/2012")},Date = DateTime.Parse("1/22/2012")},new Appointment {ClientName = "Bob",Date = DateTime.Parse("2/25/2012")},Date = DateTime.Parse("2/25/2013")}
                        };
       
        public ViewResult Test()
        {
            string str = "";
            var rs = data.Select(r=>r);
            foreach(Appointment a in rs)
            {
                str += "<li>"+a.ClientName+"</li>";
            }
            ViewBag.data = new HtmlString(str);
            return View();
        }

        [HttpPost]
        public MvcHtmlString Test(string name)
        {
            string str = "";
            var rs = data.Select(r => r);
            if ( name!= "All")
            {
                rs = rs.Where(r => r.ClientName == name);
            }
            foreach (Appointment a in rs)
            {
                str += "<li>" + a.ClientName + "</li>";
            }
            return new MvcHtmlString(str);
        }
    }

    public class Appointment
    {
        public string ClientName { get; set; }
        [DataType(DataType.Date)]
        public DateTime Date { get; set; }
        public bool TermsAccepted { get; set; }
    }

再看一下视图:
@{
    AjaxOptions ajaxOpts = new AjaxOptions
    {
        UpdateTargetId = "tabledata"
    };
}

<!DOCTYPE html>
<html>
<head>
    <Meta name="viewport" content="width=device-width" />
    <title>Test</title>
    <script src="~/Scripts/jquery-1.8.2.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
    @using (Ajax.BeginForm("Test",ajaxOpts))
    {
        <div>
            <ul id="tabledata">
                @ViewBag.data
            </ul>
        </div>
        @Html.DropDownList("name",new SelectList(
new[] { "All","Joe","Jane","Bob" },"All"))
        <input type="submit" value="Submit" />
    }
</body>
</html>
原文链接:https://www.f2er.com/ajax/164936.html

猜你在找的Ajax相关文章