Asp.net mvc 4 MVC4如何使用Ajax将json响应从存储库获取到视图中?
在MVC4网络开发方面,我是一个新手,我正在努力解决一些问题 基本上,我有以下几点:Asp.net mvc 4 MVC4如何使用Ajax将json响应从存储库获取到视图中?,asp.net-mvc-4,repository-pattern,getjson,Asp.net Mvc 4,Repository Pattern,Getjson,在MVC4网络开发方面,我是一个新手,我正在努力解决一些问题 基本上,我有以下几点: public class maincontroller: Controller { private MyRepository myRepository; public mainController() { myRepository= new MyRepository(); } public ActionResult Index() {
public class maincontroller: Controller
{
private MyRepository myRepository;
public mainController()
{
myRepository= new MyRepository();
}
public ActionResult Index()
{
var mystuff = myRepository.GetPrograms();
return View(mystuff);
}
public ActionResult MyStuff()
{
var mystuff = myRepository.GetStuff(1);
return Json(mystuff , JsonRequestBehavior.AllowGet);
}
}
假设在我的“MyRepository”类中,我有两个函数:
正在设置“mystuff”的人:
public MyRepository()
{
for (int i = 0; i < 8; i++)
{
programs.Add(new MyStuff
{
Title = "Hello" + i,
content = "Hi"
});
}
}
and second function that gets Stuff:
public List<MyStuff> GetStuff(int pageNumber = 0)
{
return stuff
.Skip(pageNumber * pageCount)
.Take(pageCount).ToList();
}
公共MyRepository()
{
对于(int i=0;i<8;i++)
{
programs.Add(新MyStuff)
{
Title=“你好”+i,
content=“你好”
});
}
}
第二个函数获取内容:
公共列表GetStuff(int pageNumber=0)
{
退货
.跳过(页码*页数)
.Take(pageCount.ToList();
}
一切都很好。我的意思是,我能够迭代“东西”并在视图上显示
问题是,我想使用AJAX显示MyStuff()
(返回Json),然后将所有内容添加到视图中。我该怎么做
我已经把头撞在墙上大约4个小时了,但我不能让它工作
如果您有任何帮助,我们将不胜感激
谢谢。在最简单的层面上,您可以使用类似的方式将HTML附加到文档中(假设您使用的是JQuery,因为它更简单):
//在当前控制器中对“MyStuff”操作进行AJAX调用
$.get(@Url.Action(“MyStuff”),函数(数据){
//循环浏览响应中的每个项目
$。每个(数据、功能(索引、项目){
//从MyStuff的JSON表示构建一些HTML
var html=“”+item.StuffProperty+”;
//将HTML附加到当前文档中的容器
$(“#容器”).append(html);
});
});
这将使用MyStuff
类中的(例如)StuffProperty
为集合中的每个项目添加一些HTML到容器元素中
像这样手动添加HTML可能是一个麻烦,一旦它变得过于复杂——在那一点上,你应该考虑使用:
部分视图(直接从控制器返回HTML,而不是JSON)
客户端模板引擎,如Mustache.js、下划线.js等,用于将JSON转换为HTML
感谢@dbaseman的快速响应。当我使用$.get(@url.Action(“MyStuff”)…
时,智能提示我`函数在当前上下文中不存在。有什么想法吗?我不知道这是错误还是我做错了什么,但无法使$。get
代码具有`函数(数据)作为一个参数。请帮助我。我可能遗漏了一些内容。@这可能意味着您尚未加载JQuery…必须在上面的脚本块之前使用
。
<div id="container"></div>
// make AJAX call to "MyStuff" action in the current controller
$.get(@Url.Action("MyStuff", function(data) {
// cycle through each item in the response
$.each(data, function(index, item) {
// construct some HTML from the JSON representation of MyStuff
var html = "<div>" + item.StuffProperty + "</div>";
// append the HTML to a container in the current document
$("#container").append(html);
});
});