【问题标题】:Json returns different stringJson返回不同的字符串
【发布时间】:2016-12-21 22:43:59
【问题描述】:

我的应用程序是 MVC 5 C#。 我正在尝试使用此 Ajax 脚本从控制器获取字符串值:

function testing() {
        $.ajax({
            url: "../../Home/Test",
            type: "GET",
            data: {
                id: 1
            },
            success: function (result) {
                if (result.PhotoURL) {
                    $("#Photo").html(result.PhotoURL);
                }
            },
            error: function (result) {
                alert("error");
            }
        });
    }

这里是控制器:

   public ActionResult Test(int id)
        {
            int updateid = 1;
            string thephoto = "<img src=\"@Url.Action(\"TheImage\",  
            new {id = " + updateid +
            "})\" class=\"mg-responsive\" style=\"margin-left: 
            auto;margin-right: auto\"/> ";
            var result = new
            {
                PhotoURL = thephoto
            };
            return Json(result, JsonRequestBehavior.AllowGet);
        }

我明白了:

   <img class="mg-responsive" style="margin-right: auto; margin-left: auto;" 
src="@Url.Action(" {id='1})"' new="" thespillimage",="">

【问题讨论】:

  • 你希望得到什么?
  • 这正是您的Test() 方法返回的内容:)。在string 中使用@Url.Action 之类的东西是没有意义的——它的剃须刀代码在服务器中进行评估,不会在您的脚本中进行评估。只需返回实际的url(在方法中使用string url = Url.Action(...);生成url
  • 谢谢斯蒂芬,它成功了。

标签: c# json ajax asp.net-mvc


【解决方案1】:

我建议先返回updateid,以便您可以在客户端构建img 标记。

public ActionResult Test(int id)
    {
        int updateid = 1;
        var result = new
        {
            PhotoId = updateid
        };
        return Json(result, JsonRequestBehavior.AllowGet);
    }

而且,在客户端

function testing() {
    $.ajax({
        url: "../../Home/Test",
        type: "GET",
        data: {
            id: 1
        },
        success: function (result) {
            if (result.PhotoId) {
                var PhotoUrl = "<img src='/YourController/TheImage/" + result.PhotoId + " class='mg-responsive' style='margin-left:         auto;margin-right: auto'/> ";
                $("#Photo").html(PhotoURL);
            }
        },
        error: function (result) {
            alert("error");
        }
    });
}

这样可以节省带宽并且很干净。如果您想更改图像上的类或属性属性,您不必重新构建解决方案。

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    相关资源
    最近更新 更多