使用Ajax Beginform

时间:2015-12-29 14:25:43

标签: c# ajax asp.net-mvc asp.net-mvc-4 razor

我刚刚创建了一个小型测试项目,看看是否可以在ASP.NET MVC Razor页面上加载不同的局部视图,但似乎我没有这样做。而不是替换"部分" div by" Partial&#34 ;,它打开" 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>

2 个答案:

答案 0 :(得分:2)

您应该将不显眼的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>
}

在布局文件中,加载jQuery库后,在最底层调用@RenderSection("scripts", required: false)。 unobtrusive-ajax脚本期望jQuery可用/已经加载。

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

因此,如果你想从其他视图中执行一些js文件,你需要在脚本部分中包含这些文件,这样当页面完全呈现时,它将被添加到底部(在其他依赖库如jQuery之后)加载);

答案 1 :(得分:1)

发现问题,jQuery没有在我的页面上定义,所以unobtrusive-ajax js文件没有正确加载。 在我不引人注意的ajax之前添加了以下参考:

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