Patrick
Patrick

Reputation: 2781

Get a JSON result based on a Ilist<int> in MVC

I need to build a string like "1-2-3-4-5", from an IList< int > returned by an MVC Action.

Action:

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 that processes the result:

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

The problem is that I get a string like this "[1,2,3,4]" in the "#adAdvancedSearchListForm #ids" HTML input, and I need to get "1-2-3-4", any idea?

Thanks.

Upvotes: 2

Views: 815

Answers (2)

Shyju
Shyju

Reputation: 218892

If you want to do it at the client side, simply iterate throught the result array and build the string you want.

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

Assuming Name and Loc are the properties of your viewmodel.

If you want to do it on the server side, you may use String.Join method to build the string representation you want. You may need to update the return type of your action method.

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

I prefer to keep my action method returns JSON result instead of this string represetnation because an action method which returns JSON can be used in many places compared to this concrete string return implementation.

Upvotes: 1

beautifulcoder
beautifulcoder

Reputation: 11340

AJAX is returning an array which is expected since you are converting a list.

Try parsing the array into the string:

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

Upvotes: 0

Related Questions