2015-09-17 64 views
2

我正在學習使用MVC 5的Ajax,它會返回整個局部視圖而不是替換div標記嗎?我不知道爲什麼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> 

這裏是腳本

<!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> 

這裏LayoutPage在頁面的局部視圖

<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(); 
     } 
    } 
} 

而且ClientValidationEnabled和UnobtrusiveJavaScriptEnabled在webconfig

回答

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> 
+0

非常感謝您,很難關注所有這些腳本庫。 –

相關問題