MVC5 Url.Action没有返回正确的URL

时间:2015-07-29 22:24:13

标签: asp.net-mvc

我正在尝试使用Kendo Grid来获取模型上的对象列表,但.Create()等方法生成的url不能正确生成url。

它似乎不仅仅是Kendo,因为即使在我的控制器中使用Url.Action()也会生成错误的网址。

// POST: Assessment/Create
[HttpPost]
[ValidateAntiForgeryToken]
[Route("eForms/Assessment/Create")] // <-- Tried with and without this
public ActionResult Create(AssessmentPoco model)
{
    var x = Url.Action(("Allergy_Read", "Assessment");
}

    //POST: Assessment/Allergy_Read
    [HttpPost, ActionName("Allergy_Read")]
    [Route("AllergyRead", Name = "Allergy_Read")]
    public ActionResult Allergy_Read([DataSourceRequest] DataSourceRequest request, AssessmentAllergiesSection model) //, int id)
    {
        return Json(new[] { model }.ToDataSourceResult(request, ModelState));
    }

预期:eForms/Assessment/Allergy_Read

实际:/?action=Allergy_Read&controller=Assessment

路线配置:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("");
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //web forms default
        routes.MapPageRoute(
            routeName: "WebFormDefault", 
            routeUrl: "", 
            physicalFile:"~/default.aspx");

        routes.MapRoute(
            name:  "API",
            url: "eforms/api/{controller}/{action}/{id}",
            defaults: new {controller="Customer", action="GetCustomers", id = UrlParameter.Optional}
            );

        ////mvc default
        routes.MapRoute(
            name: "Default",
            url: "eforms/{controller}/{action}/{id}",
            defaults: new { controller = "IncidentReports", action = "Search", id = UrlParameter.Optional }
        );
    }

不知道还有什么可能是错误的(除了我的大脑),还有什么想法?

澄清(来自评论):

  • 我们正在使用区域
  • Global.asax正在调用RegisterRoutes(也尝试将其关闭而不做更改)

更新: 该项目是现有ASP.Net WebForms应用程序新增的MVC项目。我更新了Route配置,因为我正在使用错误的配置。

2 个答案:

答案 0 :(得分:1)

您正在使用routeAttribute,因此请在其中添加名称并使用Html.RouteLink或Url.RouteUrl而不是Url.Action()。

示例:

[Route("menu", Name = "mainmenu")]
public ActionResult MainMenu() { ... }

视图中的用法:

<a href="@Url.RouteUrl("mainmenu")">Main menu</a>

答案 1 :(得分:0)

我在控制器中尝试了这段代码:

public class HomeController : Controller
   {
      [Route("AllergyRead", Name = "Allergy_Read")]   
      public ActionResult Allergy_Read()
      {
      return View();
      }
   }

和:    @ Html.RouteLink(&#34; Allergy Read&#34;,&#34; Allergy_Read&#34;)

给我正确的行动途径。我无法弄清楚你的实施工作为什么不起作用。

相关问题