13-Ajax链接与Ajax表单的快速对比Demo

前端之家收集整理的这篇文章主要介绍了13-Ajax链接与Ajax表单的快速对比Demo前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.创建mvc4 basic类型项目

2.创建Home控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcAjaxP158.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetData()
        {
            return PartialView("PartialOne");
        }
        public ActionResult GetData2()
        {
            return Content("<i>bbbb</i>");
        }
        public string LeaveMessage(FormCollection collection)
        {
            string k_Message = "标题:" + collection["yTitle"] + " Email:" + collection["yEmail"] +
                " QQ:" + collection["yQQ"] + " 内容:" + collection["yContent"];
            return k_Message;
        }      
    }
}
3.创建View,Index.cshtml内容如下:
@{
    ViewBag.Title = "Index";
}

<h2>1.Ajax链接测试</h2>
<div id="cs1"></div>
@Ajax.ActionLink("GetData","GetData",new AjaxOptions(){
    UpdateTargetId="cs1",InsertionMode=InsertionMode.InsertAfter,HttpMethod="get"})
@Ajax.ActionLink("GetData2","GetData2",InsertionMode=InsertionMode.Replace,HttpMethod="post"})
<hr />
<h2>2.Ajax表单测试</h2>
<div id="cs2"></div>
@using (Ajax.BeginForm("LeaveMessage",new AjaxOptions() {
    HttpMethod="post",UpdateTargetId="cs2" }))
{
    <p>@Html.Label("yTitle","标题")  @Html.TextBox("yTitle") </p>
    <p>@Html.Label("yEmail","电子邮件") @Html.TextBox("yEmail")</p>
    <p>@Html.Label("yQQ","QQ") @Html.TextBox("yQQ")</p>
    <p>@Html.Label("yContent","内容") @Html.TextBox("yContent")</p>
    <p><input type="submit" value="提交留言"  /></p>
    
}

@using (Ajax.BeginForm("GetData",new AjaxOptions() {
    HttpMethod="get",UpdateTargetId="cs2" }))
{   
    <p><input type="submit" value="提交"  /></p>    
}
4.在View/Home下面创建一个PartialOne局部视图,内容如下:

<i>aaaa</i>

5.在_Layout中添加一行代码:@Scripts.Render("~/bundles/jqueryval").文件内容如下:

<!DOCTYPE html>
<html>
<head>
    <Meta charset="utf-8" />
    <Meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    @RenderBody()

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryval")
    @RenderSection("scripts",required: false)
</body>
</html>

最终界面效果:

原文链接:/ajax/162158.html

猜你在找的Ajax相关文章