迭代JSON对象并收集模型值

时间:2016-03-21 11:21:37

标签: javascript jquery json ajax asp.net-mvc

我正在尝试发送一个ajax get请求,以接收数据库中我的一个表中的所有条目作为JSON对象。

检索完之后,我试图迭代所有对象并将对象ID与本地ID进行比较。

如果匹配,我想将一些html文本框设置为其值,但我无法使其工作。

JavaScript的:

$.ajax({
    url: "/Home/AllEvents",
    data: calEvent.id,
    dataType: "json",
    success: function(response) {
        for (var i = 0; i < response.length; i++) {
            var obj = response[i];

            if (obj.ID == calEvent.id)
            {
                document.getElementById('updateID').value = obj.ID;
                document.getElementById('updateType').value = obj.EventType;
                document.getElementById('updateDuration').value = obj.Hours;
                break;
            }
        }
    },

AllEvents:

public JsonResult AllEvents(double? start, double? end)
{
    var eventList = new List<object>();

    foreach (Event ev in db.Events)
    {
        eventList.Add(ev);
    }

    return Json(eventList.ToArray(), JsonRequestBehavior.AllowGet);
}

活动模型:

public int ID { get; set; }

[Required]
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date.")]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Date")]
public DateTime Date { get; set; }

[Required]
[EnumDataType(typeof(EventType), ErrorMessage = "Submitted value is not valid.")]
[Display(Name = "Type")]
public EventType? EventType { get; set; }

[Required]
public double Hours { get; set; }

[Timestamp]
public byte[] RowVersion { get; set; }

public virtual Person Person { get; set; }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

在斯蒂芬的帮助下,我设法使用以下内容:

<强> FindEvent:

public JsonResult FindEvent(int ID)
{
    Event ev = db.Events.Where(e => e.ID == ID).FirstOrDefault();

    object eventObject = new
    {
        hours = ev.Hours.ToString(),
        eventType = ev.EventType.ToString()
    };

    return Json(eventObject, JsonRequestBehavior.AllowGet);
}

<强> JavaScript的:

 $.ajax({
    url: '@Url.Action("FindEvent", "Event")',
            data: { ID: calEvent.id },
            dataType: "json",
            success: function (response) {
                console.log(response);
                document.getElementById('updateID').value = calEvent.id;
                document.getElementById('updateType').value = response.eventType;
                document.getElementById('updateDuration').value = response.hours;
            },

            error: function() {
                // Handle error
            }
        });