Ajax调用返回整个页面而不是替换div标签

时间:2015-09-17 19:07:01

标签: jquery ajax asp.net-mvc-5

我正在使用MVC 5学习Ajax,它返回整个局部视图而不是替换div标签?我不知道为什么

以下是表单提交的页面

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_LayoutPage.cshtml";
}

<h2>Index</h2>

<p>Hello from our View Template!</p>

<h3>INSERT</h3>
<div> 
 @using (Ajax.BeginForm("NewInsert","Home", new AjaxOptions  
 {  
   HttpMethod = "GET",  
   InsertionMode = InsertionMode.Replace,  
   UpdateTargetId = "formSection"  
 }))  
 {  
   <input type="text" name="textToInsert" />  
   <input type="submit" value="Insert It" />
 }
</div>
<div id="formSection">Hello</div>

这是带脚本的LayoutPage

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-2.1.4.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
</head>
<body>
    <div>
        @RenderBody()
    </div>
</body>
</html>

以下是部分视图

<h3>@ViewBag.TheText</h3>

这是控制器

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

namespace Northwind.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Welcome()
        {
            ViewBag.Message = "New page yeah";
            return View();
        }

        public ActionResult TestBeginForm()
        {
            return View();
        }
        public PartialViewResult InsertText(string text)
        {
            ViewBag.TextToDisplay = text;
            return PartialView();
        }
        public ActionResult GetText(string q)
        {
            ViewBag.TheText = q;
            return PartialView();
        }


        public ActionResult NewInsert(string textToInsert)
        {
            ViewBag.TheText = textToInsert;
            return PartialView("_NewInsert");
        }

        [HttpPost]
        public ActionResult PostInsert(string p)
        {
            ViewBag.TheText = p;
            return PartialView();
        }  
    }
}

Webconfig中的ClientValidationEnabled和UnobtrusiveJavaScriptEnabled为true

1 个答案:

答案 0 :(得分:1)

您缺少一个为您执行异步表单发布的javascript库。将其添加到您的页面(布局),您的异步表单发布应该可以正常工作。

<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-2.1.4.js"></script>

    <!--this is the new one to add-->
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
</head>