render json data returned from mvc controller

Posted by user1765862 on Stack Overflow See other posts from Stack Overflow or by user1765862
Published on 2014-06-01T21:06:37Z Indexed on 2014/06/01 21:26 UTC
Read the original article Hit count: 158

Filed under:
|
|

I'm having js function which calls mvc controller action method which return list of data as json.

function FillCountryCities(countryId) {
                $.ajax({
                    type: 'GET',
                    url: '/User/FillCityCombo',
                    data: { countryId: countryId },
                    contentType: 'application/json',
                    success: function (data) {
                        alert(data[0].Name);
                    }
                    error: function () { alert('something bad happened'); }
....

format of data which sent back from controller is Name (string) and Id (Guid)

Now I just want to alert Name on success first item from collection. Double checked controller sends 20 records, so it should alert first from collection but I'm getting error something bad happened

update:

public JsonResult FillCityCombo(Guid countryId) {
var cities = repository.GetData() .Where(x => x.Country.Id == countryId).ToList();

        if (Request.IsAjaxRequest())
        {
            return new JsonResult
            {
                Data = cities,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
        else
        {
            return new JsonResult
            {
                Data = "Not Valid Request",
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }            
    }

© Stack Overflow or respective owner

Related posts about c#

Related posts about JavaScript