我刚刚创建了一个小型测试项目,看看是否可以在 ASP.NET MVC Razor 页面上加载不同的局部 View ,但我似乎没有这样做。它不是将“部分”div 替换为“部分”,而是将“部分”作为新页面打开...
谁能告诉我我做错了什么?
现状:
概述/Index.cshtml:
@model dynamic
@{
ViewBag.Title = "title";
}
<h2>title</h2>
@Html.Partial("AnotherPartial")
概述/AnotherPartial.cshtml:
@model dynamic
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
@{
ViewBag.Title = "title";
}
<h2>title</h2>
@using(Ajax.BeginForm("Post", "Overview", new AjaxOptions{InsertionMode = InsertionMode.Replace, UpdateTargetId = "partial", HttpMethod = "POST"}))
{
<button type="submit">Submit</button>
}
<div id="partial">
</div>
报告/Partial.cshtml:
@model dynamic
@{
ViewBag.Title = "title";
}
<h2>Partial</h2>
概览 Controller :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AjaxWebTest.Controllers
{
public class OverviewController : Controller
{
// GET: Overview
public ActionResult AnotherPartial()
{
return PartialView();
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public PartialViewResult Post()
{
return PartialView("~/Views/Report/Partial.cshtml");
}
}
}
报表 Controller :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AjaxWebTest.Controllers
{
public class ReportController : Controller
{
// GET: Report
public ActionResult Index()
{
return View();
}
public ActionResult Partial()
{
return PartialView();
}
}
}
编辑: 找到解决方案:
发现问题,我的页面上没有定义 jQuery,所以 unobtrusive-ajax js 文件没有正确加载。在我的 unobtrusive-ajax include 之前添加了以下引用:
<script src="~/Scripts/jquery-1.10.2.js"></script>
最佳答案
您应该将 unobtrusive-ajax 脚本引用放在主视图的 Scripts
部分。
@model dynamic
@{
ViewBag.Title = "title";
}
<h2>Main Index page title</h2>
@Html.Partial("AnotherPartial")
@section Scripts
{
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
}
在布局文件中,@RenderSection("scripts", required: false)
在加载 jQuery 库后在最底部被调用。 unobtrusive-ajax 脚本期望 jQuery 可用/已经加载。
<div id="pageContent">
@RenderBody()
</div>
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
所以如果你想从你的其他 View 执行一些js文件,你需要将它们包含在脚本部分,这样当页面完全呈现时,它会被添加到底部(在其他依赖库如jQuery之后已加载);
关于c# - 使用 Ajax Beginform 加载不同的局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34513036/