我有这个动作方法:
[HttpPost]
public ActionResult GetNextImage(int m_id)
{
...
return Json(new{...});
}
我这样调用它:
$(function () {
$('#nextImage').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: "m_id=" + $('#img').attr('alt'),
success: function (result) {
$('#img').attr("src", result.imagePath);
$('#img').attr("alt", result.ImageId);
}
});
return false;
});
});
我有Image对象
public class Image
{
public int ImageId {get;set;}
public string imagePath {get;set;}
public List<Comment> Comments {get;set;}
}
现在。是否可以从动作方法返回我的“图像”对象并绑定它? 我不知道如何用JSon加载评论列表。这就是为什么我想要返回对象并使用简单的循环来显示所有注释。但是我不知道如何从action方法返回对象并将其绑定到(razor)页面。
答案 0 :(得分:5)
简单地回答你的问题,是的,你可以绑定你的图像对象并返回对象。请参阅下面的代码。我略微简化了我的示例,但我认为它提供了一个足够的示例,您可以根据自己的目的进行查看和修改。例如,我只是使用一个按钮并绑定click事件来调用ImageController的GetImage方法,而不是像原始问题那样使用表单。
查看
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Sandbox.Models.Image>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Image Test</title>
<script type = "text/javascript" src="../../Scripts/jquery-1.5.1.min.js"></script>
<script type = "text/javascript">
$(document).ready(function () {
$('#nextImage').click(function () {
$.ajax({
url: "Image/GetImage",
type: "post",
data: "m_id=" + $('#img').attr('alt'),
success: function (image) {
$('#img').attr("src", image.ImagePath);
$('#img').attr("alt", image.ImageId);
//here is where we loop over the list of comments
//associated with the Image JSON object that is returned
//from the controller. here 'val' is the Comment model
//and .Data simply calls the string member containing the
//actual comment
$.each(image.Comments, function (index, val) {
$('#comments').append("<div>" + val.Data + "</div>");
});
}
});
});
});
</script>
</head>
<body>
<img alt="1" id="img" src=""/>
<button id="nextImage">Next</button>
<div id="comments"></div>
</body>
</html>
控制器
public class ImageController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetImage(int m_id)
{
Image image = new Image {
ImageId = m_id,
ImagePath = "Content/mandrill.png",
Comments = new List<Comment>
{
new Comment {Data = "I love it"},
new Comment {Data = "I love it also!"}
}};
return Json(image);
}
}
模型
public class Image
{
public int ImageId { get; set; }
public string ImagePath { get; set; }
public List<Comment> Comments { get; set; }
}
public class Comment
{
public string Data { get; set; }
}
希望这有帮助