Как представить массив объектов JSON через ActionResult - PullRequest
2 голосов
/ 02 февраля 2012

У меня есть следующий код:

private ActionResult Foo(string format, IEnumerable<String> myResults)
    {
        if (format == "JSON")
        {
            return ConvertToAnJsonActionResult(myResults); // GetJsonResults(sm);
        }
        else //turn to html and return
        {
            return View("Index", myResults);
        }
    }

myResults - это коллекция строк JSON. Мне нужно преобразовать его в ActionResult, который содержит этот массив JSON, и отправить его клиенту. Как мне это сделать?

Я пытался return Json(myResults), который возвращает JsonResult, но тогда я являюсь JSON, кодирующим коллекцию объектов JSON, в результате чего \ добавляется к каждому ", когда клиент получает результаты.

Ответы [ 4 ]

1 голос
/ 02 февраля 2012

Я переопределил JsonResult:

public class ArrayJsonResult : System.Web.Mvc.JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
            String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("JsonRequest_GetNotAllowed");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            StringWriter sw = new StringWriter();
            sw.Write("[");
            try
            {
                var collection = Data as IEnumerable<String>;
                int countLessOne = collection.Count() -1;
                for (int i = 0; i < countLessOne; i++ )
                {
                    sw.Write(collection.ElementAt(i));
                    sw.Write(",");
                }
                sw.Write(collection.ElementAt(countLessOne));
            }
            catch (Exception)
            {
                //data was not a collection
            }

            sw.Write("]");
            response.Write(sw.ToString());
        }
    }
1 голос
/ 02 февраля 2012

Возвращение JsonResult сделает всю работу.JsonResult наследует ActionResult, вы можете проверить эту ссылку. ActionResults

0 голосов
/ 02 февраля 2012

Поскольку смешивание json и non-json не поддерживается никаким встроенным методом, лучше всего вручную построить и вернуть массив json:

return Content( 
    myResults.Aggregate(
        new StringBuilder("[\""),
        (sb,r) => sb.Append(r).Append('","'),
        sb => sb.RemoveAt(sb.Length-2,2).Append("]").ToString()
    ),
    "application/json" 
);
0 голосов
/ 02 февраля 2012

Возвращает JsonResult вместо ActionResult.

Быстрый поиск в Google обнаружил эту запись в блоге ...

http://shashankshetty.wordpress.com/2009/03/04/using-jsonresult-with-jquery-in-aspnet-mvc/

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...