我只是创建了一个小测试项目,以查看是否有可能在ASP.NET MVC Razor页面上加载不同的局部视图,但似乎我没有这样做。而不是将“ partial” div替换为“ Partial”,而是将“ Partial”作为新页面打开...

谁能告诉我我在做什么错?

现在的情况:

概述/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>


OverviewController:

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


ReportController:

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文件未正确加载。在不引人注目的ajax之前添加了以下参考:

<script src="~/Scripts/jquery-1.10.2.js"></script>

最佳答案

您应该将不引人注目的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库后在最底部被调用。简洁的ajax脚本期望jQuery可用/已经加载。

<div id="pageContent">
    @RenderBody()
</div>
@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)


因此,如果要从其他视图执行一些js文件,则需要在脚本部分中包括这些文件,以便在页面完全呈现后将其添加到底部(在加载其他类似jQuery的依赖库之后);

关于c# - 使用Ajax Beginform加载不同的局部 View ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34513036/

10-11 12:36
查看更多