Chr*_*ris 8 c# asp.net-mvc json razor asp.net-mvc-4
我有一个AddressBook控制器,它将返回一个"文件夹"列表(基本上是组/位置).这可以在渲染时通过AJAX请求或在MVC页面本身中调用.
如何创建一个适用于这两种情况的功能?这是我当前的Controller动作,我似乎很难在我的MVC页面中使用
public ActionResult GetFolderList(int? parent)
{
List<String> folderList = new List<String>();
folderList.Add("East Midlands");
folderList.Add("West Midlands");
folderList.Add("South West");
folderList.Add("North East");
folderList.Add("North West");
return Json(folderList);
}
Run Code Online (Sandbox Code Playgroud)
在页面内(不工作atm)
@{
var controller = new My.Controllers.AddressBookController();
var what = controller.GetFolderList(0);
foreach(var p in what){
//i want to get the list items here
}
}
Run Code Online (Sandbox Code Playgroud)
只需要一个返回的函数List,然后在你的页面加载和AJAX请求Action方法中调用它.
就像是:
public List<string> GetFolderList()
{
List<String> folderList = new List<String>();
folderList.Add("East Midlands");
folderList.Add("West Midlands");
folderList.Add("South West");
folderList.Add("North East");
folderList.Add("North West");
return folderList;
}
Run Code Online (Sandbox Code Playgroud)
然后在页面加载时,您可以将其粘贴在您的模型中:
public ActionResult Index()
{
var model = new YourViewModel(); //whatever type the model is
model.FolderList = GetFolderList(); //have a List<string> called FolderList on your model
return View(model); //send model to your view
}
Run Code Online (Sandbox Code Playgroud)
然后在您的视图中,您可以:
@model YourViewModel
@{
foreach(var item in Model.FolderList){
//do whatever you want
}
}
Run Code Online (Sandbox Code Playgroud)
然后,假设你的ajax请求是这样的:
$.ajax({
url: '@Url.Action("GetFolders", "ControllerName")',
type: 'POST',
datatype: 'json',
success: function (result) {
for (var i = 0; i < result.length; i++)
{
//do whatever with result[i]
}
}
});
Run Code Online (Sandbox Code Playgroud)
您的GetFolders操作方法如下所示:
public ActionResult GetFolders()
{
return Json(GetFolderList());
}
Run Code Online (Sandbox Code Playgroud)
这将有效:
public ActionResult GetFolderList(int? parent)
{
List<String> folderList = new List<String>();
folderList.Add("East Midlands");
folderList.Add("West Midlands");
folderList.Add("South West");
folderList.Add("North East");
folderList.Add("North West");
if(Request.IsAjaxRequest())
{
return Json(folderList);
}
return View("someView", folderList );
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |