我花了一段時間才弄清楚如何讓angularjs與asp.net mvc一起工作 - 這不是100%你做事的方式,但你可能想重新考慮這種方法(它是沒有太大不同)
var AccountApp = angular.module("AccountApp", ['$strap.directives', 'ngResource', 'ngGrid', 'filePickers']).
config(function ($routeProvider) {
$routeProvider.
when('/', { controller: ListCtrl, templateUrl: 'Templates/Account/List' }).
when('/', { controller: EditCtrl, templateUrl: 'Templates/Account/Edit' }).
otherwise({ redirectTo: '/' });
});
好的,請注意我打電話給模板/帳戶/列表。
在我RouteConfig.cs
routes.MapRoute(
name: "Templates",
url: "Templates/{controller}/{template}",
defaults: new { action = "Template" }
);
在每個控制器
現在,我有一個指導調用適當的局部視圖此相應的動作:
public ActionResult Template(string template)
{
switch (template.ToLower())
{
case "list":
return PartialView("~/Views/Account/Partials/List.cshtml");
case "create":
return PartialView("~/Views/Account/Partials/Create.cshtml");
case "edit":
return PartialView("~/Views/Account/Partials/Edit.cshtml");
case "detail":
return PartialView("~/Views/Account/Partials/Detail.cshtml");
default:
throw new Exception("template not known");
}
}
這一切都開始與索引()在控制器中的行爲。
public ActionResult Index()
{
return View();
}
把它放在一起,我的目錄結構看起來像這樣。
/Views
/Account
/Partials
List.cshtml
Create.cshtml
Edit.cshtml
Detail.cshtml
Index.cshtml
我有偏見,因爲這是我的方法,但我認爲它使事情變得非常簡單,組織得很好。 Index.cshtml包含ng-view,並且該應用程序的所有其他部分都很好地包含在通過該模板操作加載的部分視圖中。希望這可以幫助。
我想我會做類似的事情,但用'返回新的PartialView(「〜/ Views/Account/Partials /」+ template +「.cshtml」);或者甚至嘗試映射路徑和檢查文件是否先存在並嘗試備用文件夾。 –
葛厚德給出的解決方案更好,我也在使用該解決方案。不要搞亂路由器,只要爲你的局部視圖創建動作,並讓MVC完成它的工作。 – Alisson