gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:44:08 25 4
gpt4 key购买 nike

我正在使用 MVC 5 学习 Ajax,它返回整个部分 View 而不是替换 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>

这是部分 View

<h3>@ViewBag.TheText</h3>

这是 Controller

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

最佳答案

您缺少一个为您执行异步表单发布的 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>

关于jquery - Ajax 调用返回整个页面而不是替换 div 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32638164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com