【问题标题】:404.15 not found MVC4 RazorJS404.15 未找到 MVC4 RazorJS
【发布时间】:2015-02-26 10:24:10
【问题描述】:

我在我的MVC4 应用程序中使用RazorJS 在Js 文件中使用Razor 语法“@”。

//代码:

@Html.RazorJSInclude("~/Scripts/Application/Transactions.js")
<button id="btnSearch" name="submit" type="button" onclick="Loadgrid();">Search</button>

“Transaction.js”内部有“LoadGrid”方法。当我使用我的 Transaction.js 作为上面的代码时,它会抛出错误,因为“没有找到这样的方法(Loadgrid)”。

浏览器中呈现的 HTML 显示如下,

<SCRIPT src="/razorjs.axd?fn=/Scripts/Application/Transactions.js" type="text/javascript"></SCRIPT>

当我尝试这样使用时,

<script src="~/Scripts/Application/Transactions.js"></script>
@Html.RazorJSInclude("~/Scripts/Application/Transactions.js")

浏览器接受了 js 文件,但 js 文件内的 ajax 调用没有被调用,并抛出以下异常作为警报。

IIS 8.0 Detailed Error-404.15-Not Found

带有一些 html 内容。

//js文件中的代码

function Loadgrid() {

    $.ajax({
        url: '@Url.Action("LoadColumns", "Home")',
        data: { 'workflowId': '5' },
        datatype: 'json',
        type: 'GET',
        cache: false,
        success: OnComplete,
        error: function (xhr, status, error) {
                alert(xhr.statusText);
                window.location.href = '@Url.Action("LogOut", "Account")';
        }
    });
}

//控制器:

    public ActionResult LoadColumns(string workflowId)
    {
      return Content("Success");
    }

加载列方法未命中。我哪里错了?

仅供参考,

url: '/Home/LoadColumns' 之类的 ajax 调用中使用 url 时,代码运行良好,但仅在本地计算机中而不是在服务器中(开发中的主机)。

RazorJS 版本是 0.4.3

来源:Razor inside Js file

【问题讨论】:

  • 虽然我没有答案,但我还是要感谢您将我指向 RazorJS,这是我经常需要的东西。
  • 顺便说一句:您是否将应用程序安装在服务器的子目录中?
  • @jao:不。它就在 wwwroot 下。
  • @jao:使用 colsole.log 将值显示为 @Url.Action("LoadColumns", "Home")
  • @InvernoMuto:不,我没有使用 ViewModel。完全在 javascript 中使用。

标签: asp.net-mvc asp.net-mvc-4 razor razorengine


【解决方案1】:

您在 ajax 调用中指定 datatype: 'json',但您的控制器操作 return Content("Success"); 其中内容将是纯文本并且不允许,更改为 return Json(new { foo = "bar", baz = "Blech" }, JsonRequestBehavior.AllowGet),然后,您说脚本中的 ajax 调用是没有被调用,然后你说你检索到一个警报,这个警报:

alert(xhr.statusText);

所以您的函数按预期调用。不要使用alerts来调试,试试:

console.log(error);

您首选的开发人员工具的网络选项卡也会比警报做得更好。

Here you can find a simple working example完成你的任务:

\Views\Home\Index.cshtml

@Html.RazorJSInclude("~/Scripts/App/TestRazorJS.js")
<button id="btnSearch" name="submit" type="button" onclick="LoadFromRazor()">Search</button>

\Scripts\App\TestRazorJS.js

function LoadFromRazor() {
  $.ajax({
    url: '@Url.Action("Test", "Home")',
    datatype: 'json',
    type: 'GET',
    cache: false,
    success: function () { console.log('done'); },
    error: function (xhr, status, error) {
      console.log(status);

    }
  });
}

\Controllers\HomeController.cs

public ActionResult Test()
    {
      return Json(new { foo = "bar", baz = "Blech" }, JsonRequestBehavior.AllowGet);
    }

它按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多