【问题标题】:Asp.Net MVC Routing and URL IssueAsp.Net MVC 路由和 URL 问题
【发布时间】:2017-11-15 15:20:53
【问题描述】:

首先,感谢您的回答。我对 Asp.Net MVC 上的路由有疑问。

您可以在我的控制器和视图所在的照片上看到我的解决方案。我想从“Index.cshtml”打开“UserProfile.cshtml”。好吧,我的第一种方法是使用 Ajax 在 ProfileController 中发布“UserProfile Action”。

 $.ajax({
        url: "/Profile/UserProfile",
        type: "POST",
        dataType: "json"})
           .done(function(response){
               window.location = '/Profile/UserProfile'});

此代码块进入控制器并点击“UserProfile”操作,但没有返回错误和视图。甚至 URL 也不会改变。

   public ActionResult UserProfile()
    {
       return View ();
    }

非常感谢您提供有用的回答和支持。谢谢!

【问题讨论】:

  • ASP.NET Core 无法处理 aspx 页面
  • 您的视图需要是 Razor (.cshtml) 视图,并且默认路由在 App_Start 文件夹的 RouteConfig.cs 中定义
  • @peggy 谢谢。我已经更改为cshtml。它解决了 View 的 URL 问题。但下面的代码块仍然没有返回任何内容。它击中了那里,但没有错误,也没有再次查看。 public ActionResult UserProfile() { return View (); }
  • @Johnny 查看发布的答案。如果您仍有问题,请发布更新的屏幕截图,显示您已将视图更改为剃刀并发布视图代码。
  • 你为什么要使用window.location = '/Profile/UserProfile' - 使用ajax 的全部意义在于保持在同一页面上。如果要重定向,请不要使用 ajax。并且您指定 dataType: 'json' 但您的方法返回 html ,这样会引发错误。 Remove the dataType`选项,改变方法返回一个PartialView并在回调中更新DOM——.done(function(response){ #(someElement).html(response); }更新当前页面

标签: c# asp.net asp.net-mvc routing


【解决方案1】:

首先,您需要有 Razor (.cshtml) 视图,而不是 aspx 以便 mvc 能够开箱即用地为这些页面提供服务。如果您在ProfileController 中有一个名为UserProfile 的控制器操作并调用return View(),则mvc 将默认尝试返回位于Views/Profile/UserProfile.cshtml 的视图(它实际上还会检查其他几个位置,例如视图/Shared/ 文件夹用于视图)。以下内容应该适合您:

//located in ProfileController
[HttpPost]
public ActionResult UserProfile()
{
   return View();
}

//located at Views/Profile/UserProfile.cshtml
`<h4>you've found your user profile page!</h4>`

如果您试图通过 ajax- 来解决这个问题,那么您需要从稍微不同的方向来解决问题。服务器端的重定向不适用于 ajax,因为它是异步的。您可以通过使用.done() ajax 回调来实现这一点,如下所示:

 $.ajax({
     url: "/Profile/UserProfile",
     type: "POST",
     dataType: "json"
 }).done(function(response){
     window.location = '/Profile/UserProfile'
 });

【讨论】:

  • 我根据您的建议在这里编辑了我的问题。您可以在那里看到屏幕截图和代码。但问题还是一样。它在运行中命中断点,但没有返回错误并再次查看。
  • @Johnny ajax .done 回调中的断点是否被命中?此外,如果您使用 ajax,则更常见的是在控制器操作中返回 JsonResultPartialView,然后通过 response 对其进行操作(显示部分视图或对 json 数据执行某些操作) .done 回调中的对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 2014-12-09
  • 2011-11-11
  • 2013-11-13
相关资源
最近更新 更多