Member 13449171 Ответов: 0

Как я могу заполнить массив свойствами модели в действии контроллера и перейти к просмотру?


Hi. I have a model with a table namely Resource that consist of multiple properties. I want define an array and fill that with Id,Latitude and Longitude properties in action namely DistanceMCalculate() in controller and pass this array to javascript in view in my MVC project.


this is my model in edmx:

    
public partial class Resource
    {
        public int Id { get; set; }
        public int Code { get; set; }
        public string Name { get; set; }
        public Nullable<System.DateTime> StartHour { get; set; }
        public string Address { get; set; }
        public Nullable<System.DateTime> Arrivetime { get; set; }
        public Nullable<int> ArriveTimeDuration { get; set; }
        public Nullable<int> ProgressPercent { get; set; }
        public Nullable<int> ResourceTypeId { get; set; }
        public Nullable<decimal> Latitude { get; set; }
        public Nullable<decimal> Longitude { get; set; }

        public virtual ResourceType ResourceType { get; set; }
    }
}

this is my action and I want add Id,Latitude and Longitude properties of model to an arraylist and pass to view in javascript. I need just array in view.how can I do it?

public ActionResult DistanceMCalculate()
        {
            var model= db.Resource.Where(p => p.ResourceTypeId == 1 && p.Latitude != null).ToList();
           
            return Json();
        }

Thanks a lot


Что я уже пробовал:

public JsonResult DistanceMCalculate()
       {
           var origins = db.Resource.Where(p => p.ResourceTypeId == 1 && p.Latitude != null).ToList();
           //decimal?[] array = new decimal?[3];
           ArrayList a = new ArrayList();
           ArrayList list = new ArrayList();
           foreach (var item in origins)
           {
               a[0] = item.Id;
               a[1] = item.Latitude;
               a[2] = item.Longitude;
               list.Add(a);
           }
           //ViewBag.originsArry = origins.ToArray();
           ViewBag.list = JsonConvert.SerializeObject(list);

           return Json(ViewBag.list, JsonRequestBehavior.AllowGet);
       }


У меня есть ошибка в строке
ViewBag.list = JsonConvert.SerializeObject(list);

Richard MacCutchan

Какая ошибка?

F-ES Sitecore

Не используйте ViewBag, не используйте ArrayList. Либо создайте конкретные классы, которые могут моделировать ваши данные и составлять их список, либо используйте анонимные типы.

var returnData = происхождение.Выберите (item => new {
ИД = товар.Идентификатор,
Широта = пункт.Широта,
Долгота = пункт.Долгота
});

затем преобразуйте "returnData" в JSON, чтобы вернуться из вашего метода. Проблема с вашим кодом заключается в том, что вы обнаружите, что просто добавляете одни и те же данные снова и снова, и у вас будет список последнего объекта, и, вероятно, также конвертер json не имеет допустимого имени свойства для использования в json, поскольку вы используете ArrayList, который не имеет понятия "имя".
});

0 Ответов