2016-12-21 64 views
0

我的應用程序是MVC 5 C#。 我試圖讓使用此阿賈克斯腳本控制器的字符串值:Json返回不同的字符串

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",=""> 
+0

你希望得到什麼? – ADyson

+0

hncl

+1

這就是你的'Test()'方法返回:)。在'string'中使用諸如'@ Url.Action'這樣的東西是毫無意義的 - 在服務器中評估它的剃刀代碼並且不會在腳本中進行評估。只需返回實際的URL(使用'string url = Url.Action(...);'在方法 –

回答

0

我會建議返回首先是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"); 
     } 
    }); 
} 

這節省了帶寬,它是乾淨的。如果要更改圖像上的類或屬性屬性,則不必重新構建解決方案。