ASP MVC Ajax и повторная привязка модели - PullRequest
2 голосов
/ 07 ноября 2011

У меня есть этот метод действия:

[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;
        });
    });

У меня есть объект изображения

public class Image
{
    public int ImageId {get;set;}
    public string imagePath {get;set;}
    public List<Comment> Comments {get;set;}
}

Сейчас.Возможно ли вернуть из метода действия мой объект «Образ» и связать его?Я не знаю, как загрузить список комментариев с JSon.Вот почему я хочу вернуть объект и с простым циклом для отображения всех комментариев.Но я не знаю, как вернуть объект из метода действия и связать его со страницей (бритвой).

1 Ответ

5 голосов
/ 07 ноября 2011

Чтобы ответить на ваш вопрос просто, да, вы можете связать свой объект изображения и вернуть объект. Пожалуйста, смотрите код ниже. Я немного упростил свой пример, но я думаю, что он предоставляет достаточный пример, который вы можете просмотреть и изменить для своих собственных целей. Например, вместо того, чтобы использовать форму, подобную вашему первоначальному вопросу, я просто использую кнопку и привязываю событие click для вызова метода GetImage ImageController.

View

<%@ 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; }
}

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...