2014-02-21 36 views
2

根據ILIST 我需要建立像「1-2-3-4-5」的字符串,從一個IList < int>的由MVC操作返回。 得到一個JSON結果MVC

操作:

public virtual JsonResult AdvancedSearch(AdAdvancedSearchViewModel asViewModel) 
{ 
    IList<int> adIds = new List<int>(); 

    try 
    { 
     var asDto = Mapper.Map<AdAdvancedSearchViewModel, AdAdvancedSearchDto>(asViewModel); 

     adIds = _adService.AdvancedSearch(asDto); 
    } 
    catch 
    { 
     adIds = null; 
    } 

    return Json(adIds); 
} 

JavaScript函數,處理結果:

function onAdAdvancedSearchSuccess(jsonAdListIds) 
{ 
    $("#adAdvancedSearchListForm #ids").val(jsonAdListIds); 
} 

的問題是,我得到一個字符串,像這樣的 「[1,2,3,4]」 的「#adAdvancedSearchListForm #ids」 HTML輸入,我需要得到「1-2-3-4」,任何想法?

謝謝。

回答

0

AJAX正在恢復它,因爲要轉換列表預計的數組。

嘗試陣列解析成字符串:

var r = jsonAdListIds[0]; 
for (var i = 1; i < jsonAdListIds.length; i++) { 
    r += '-' + jsonAdListIds[i]; 
} 
+0

嗨,謝謝,它工作的很棒! ;) – Patrick

1

如果你想在客戶端做,只是重複throught結果數組,並建立你想要的字符串。

$.getJSON("yourURL", { Name: "John", Loc: "2pm" },function(result){ 
    var str=""; 
    $.each(result,function(i,item){ 
     str=str+"-"+item; 
    }); 
    alert(str); 
}); 

假設Name和Loc是你的viewmodel的屬性。

如果你想這樣做在服務器端,您可以使用String.Join方法來建立你想要的字符串表示。您可能需要更新您的操作方法的返回類型。

public string AdvancedSearch(AdAdvancedSearchViewModel asViewModel) 
{ 
    List<int> adIds = new List<int>(); 
    //fill the list 
    var resutlStr= String.Join("-",adIds.ToArray()); 
    return resutlStr; 
} 

我寧願讓我的操作方法返回JSON結果,而不是該字符串represetnation的,因爲可以在很多地方使用它返回JSON的操作方法相比,這種具體的字符串返回執行。

+0

我的理解是一個Ajax響應需要一個'JsonResult'所以這可能無法正常工作。 – beautifulcoder

+0

ajax也可以接收字符串。但是,理想的解決方案是讓你的服務器端方法返回JSON,因爲它可以在很多地方使用 – Shyju

+0

感謝您好,我更喜歡的方式simpliest答案@beautifulcoder適應我的代碼。無論如何感謝您 – Patrick