从外部装配项目调用控制器时出错

时间:2018-01-22 06:04:56

标签: jquery asp.net ajax asp.net-mvc

这是我的jQuery代码,它从timeclock.controller类库项目调用Controller:

  function getCountries()
  {
           // alert();
            var obj = {};
            obj.countryName = '';
            $.ajax({
                type: 'GET',
                url: '/Business/GetCountries',
                dataType: 'json',
                async: false,
                success: function (data) {

                    console.log(data);



                },
                error: function (err) {

                    console.log(err);
                }
            });

  }

这是我要调用的另一个类库项目的控制器:

namespace timeclock.controller
{
    class BusinessController : System.Web.Mvc.Controller
    {
        [HttpGet]
        [Route("Countroller/GetCountries")]
        public JsonResult GetCountries(string countryName)
        {
            //List<countries_model> countrylist = null;
            var myresult = "{'name':'John', 'age':31, 'city':'New York' }";
            return Json(myresult,JsonRequestBehavior.AllowGet);
        }
    }
}

这是我主要项目的路线配置文件:

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "signup", id = UrlParameter.Optional },
               namespaces: new[] { "timeclock.controller" }
            );

            routes.MapMvcAttributeRoutes();
}

2 个答案:

答案 0 :(得分:0)

最后我得到了解决方案  只需删除路由配置中的操作

 routes.MapRoute(
  name: "Business",
  url: "{controller}/{action}/{id}",
 defaults: new { controller = "Business", id = UrlParameter.Optional }
);

答案 1 :(得分:0)

问题是您的路线定义错误。如果您希望任何具有1,2或3段网址的MapMvcAttributeRoutes属性能够正常运行,则Default必须位于[Route]路线之前。

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

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "signup", id = UrlParameter.Optional },
       namespaces: new[] { "timeclock.controller" }
    );
}

参考:Why map special routes first before common routes in asp.net mvc?