更新下拉列表更改事件

时间:2015-10-12 16:43:25

标签: jquery asp.net-mvc asp.net-mvc-4 fullcalendar

在下拉列表中的更改事件中,我需要更新部分ViewModel和fullcalendar jquery插件上的事件。更新插件上的事件我已经工作了。但我不明白更新ViewModel.Team视图的最佳方法。这是我的第一个MVC应用程序。这是MVC4。 这是我的标记。我使用多个模型作为控件。

<div id="manual_select_div" style="margin-top: 5px; border: 1px solid black; width: 100%; height: 50%">             
    <div id="selectList">
        <label id="team_lbl">Team Members: </label>
        @foreach (var member in Model.Team)
        {
            <div id="@member.member_id.ToString()" style="font-weight:bold; background-color:@member.member_color" class="draggable"
                    data-event='{"title":"@member.member_name", "color":"@member.member_color"}'>@member.member_name</div>
        }
    </div>     
</div>
<div id='edit_calendar' style="float:right; width: 60%; height: 70%"></div> 

最初显示数据时,我对日历使用AJAX调用,为团队成员数据使用多个模型。

public ActionResult EditSchedule()
{
    string tstrUserID = string.Empty;
    EditScheduleViewModel editScheduleModel = new EditScheduleViewModel();
    try
    {
        //Get the UserID value
        tstrUserID = ParseUserID(this.User.Identity.Name);

        DataTable tdtTeamInfo = new DataTable();        
        List<string> tlstGroupIDs = new List<string>();

        //Database calls to get all of the data
        //Get the group information that user has the admin rights to edit schedule
        tdtGroupInfo = onCallDA.GetGroupByUserID(tstrUserID);
        //Get Team information using first groupID
        int tiGroupID = tdtGroupInfo.Select().First().Field<int>("ID");
        tdtTeamInfo = onCallDA.GetGroupMembersByGroupID(tiGroupID);
        //Populate the ViewModel
        List<Group> groups = tdtGroupInfo.AsEnumerable().Select(x => new Group
        {
            id = (string)(x["ID"].ToString()),
            name = (string)(x["Name"]),
            color = (string)(x["GroupColor"])
        }).ToList();

        editScheduleModel.Groups = groups;

        List<Member> team = tdtTeamInfo.AsEnumerable().Select(x => new Member
            {
                group_id = (string)(x["GroupID"].ToString()),
                member_id = (string)(x["MemberID"].ToString()),
                member_name = (string)(x["MemberName"]),
                member_color = (string)(x["MemberColor"])
            }).ToList();

        editScheduleModel.Team = team;

        return View(editScheduleModel);

    }
    catch(Exception ex)
    {
        return View("Error");
    }          
}

这是onchange事件。日历已正确更新:

$("#group_name_select").change(function(){
    var groupSelected = $(this).val();
    var groupData = { iGroupID: groupSelected };

    $('#edit_calendar').fullCalendar('removeEvents');
    $('#edit_calendar').fullCalendar('addEventSource', function (start, end, timezone, callback) {
        $.ajax({
            type: "POST",
            url: '@Url.Action("GetEventsForGroup", "Home")',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(groupData),
            success: function (doc) {
                var events = [];
                $(doc).each(function () {
                    events.push({
                        title: $(this).attr('title'),
                        start: $(this).attr('start'),
                        end: $(this).attr('end'),
                        id: $(this).attr('eventID'),
                        groupID: $(this).attr('objectID'),
                        color: $(this).attr('color'),
                        textColor: 'black'
                    });
                });
                callback(events);
            },
            error: function () {
                alert("There was an error fetching events!")
            }
        });
    });
});

为了完整性......这就是在文档就绪函数中初始化日历插件的方式:

$(document).ready(function () {     
// page is now ready, initialize the calendar...
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();

//Get the group from the dropdown to populate calendar    
var groupSelected = $('#group_name_select').val();
var groupData = { iGroupID: groupSelected };

$('#edit_calendar').fullCalendar({
    header:
    {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    titleFormat: { month: 'MMMM' },
    defaultView: 'month',
    selectable: true,
    selectHelper: true,
    droppable: true,
    editable: true,
    eventSources: [
       {
           events: function (start, end, timezone, callback) {
               $.ajax({
                   type: "POST",
                   url: '@Url.Action("GetEventsForGroup", "Home")',
                   data: JSON.stringify(groupData),
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   success: function (doc) {
                       var events = [];
                       $(doc).each(function () {
                           events.push({
                               title: $(this).attr('title'),
                               start: $(this).attr('start'),
                               end: $(this).attr('end'),
                               id: $(this).attr('eventID'),
                               objectID: $(this).attr('objectID'),
                               color: $(this).attr('color'),
                               textColor: 'black',
                               editable: true
                           });

                       });
                       callback(events);
                   },
                   error: function () {
                       alert("There was an error fetching events!")
                   }
               });
           }
       }
    ],
    eventResizeStart: function (event, jsEvent, ui, view) {
        console.log('RESIZE START ' + event.title);

    },
    eventResizeStop: function (event, jsEvent, ui, view) {
        console.log('RESIZE STOP ' + event.title);
    },

    eventResize: function (event, dayDelta, minuteDelta, revertFunc) {

        if (dayDelta >= 1 && !event.allDay) {
            revertFunc();

            for (var i = 0 ; i < dayDelta ; i++) {
                var newEvent = {
                    id: event.id,
                    objectID: event.objectID,
                    title: event.title,
                    color: event.color,
                    textColor: 'black',
                    start: new Date(event.start),
                    end: new Date(event.end),
                    allDay: event.allDay
                };

                newEvent.start.setDate(newEvent.start.getDate() + (i + 1));
                newEvent.end.setDate(newEvent.end.getDate() + (i + 1));
                $('#edit_calendar').fullCalendar('renderEvent', newEvent, 'stick');
            }
        }
    }
}); //end calendar initialization

//...other initialization stuff not relevant

}); //End document ready function

我的问题是如何更新editScheduleModel.Team模型?应该像日历插件一样进行AJAX调用吗?如何更新模型?我应该更改团队数据的初始化方式并使用AJAX调用吗?

感谢您的帮助。

更新 我不知道这是否是最好的方法..但我将以下代码添加到jquery更改函数以更新团队成员列表:

 $("#group_name_select").change(function(){
    var groupSelected = $(this).val();
    var groupData = { iGroupID: groupSelected };
    $.ajax({
        type: "POST",
        url: '@Url.Action("UpdateTeamMembers", "Home")',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(groupData),
        success: function(team) {
            $(team).each(function () {
                alert('Team member: ' + $(this).attr('member_name'));
            });
        },
        error: function() {
            alert("There was an error fetching events!")
        }          
    });

警报中显示正确的名称。 Controller方法是:

 public ActionResult UpdateTeamMembers(int iGroupID)
    {
        DatabaseAccess onCallDA = new DatabaseAccess();
        DataTable tdtTeamInfo = new DataTable();
        try
        {
            tdtTeamInfo = onCallDA.GetGroupMembersByGroupID(iGroupID);
            List<Member> team = tdtTeamInfo.AsEnumerable().Select(x => new Member
            {
                group_id = (string)(x["GroupID"].ToString()),
                member_id = (string)(x["MemberID"].ToString()),
                member_name = (string)(x["MemberName"]),
                member_color = (string)(x["MemberColor"])
            }).ToList();

            return Json(team, JsonRequestBehavior.AllowGet);
        }
        catch(Exception)
        {
            throw;
        }           
    }

我不知道如何在html中设置值。最初,我使用Team模型设置值:

<div id="selectList">
        <label id="team_lbl">Team Members: </label>
        @foreach (var member in Model.Team)
        {
            <div id="@member.member_id.ToString()" style="font-weight:bold; background-color:@member.member_color" class="draggable"
                    data-event='{"title":"@member.member_name", "color":"@member.member_color"}'>@member.member_name</div>
        }
    </div>     

但是如何在jquery更改函数中设置上面的值?

更新

我可以更新change事件中的'divs',如下所示:

 $("#group_name_select").change(function(){
    var groupSelected = $(this).val();
    var groupData = { iGroupID: groupSelected };
    $.ajax({
        type: "POST",
        url: '@Url.Action("UpdateTeamMembers", "Home")',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(groupData),
        success: function(team) {
            $('div').remove('.draggable');
            $(team).each(function () {
                $('#selectList').prepend('<div id="' + $(this).attr('member_id') + '" style="font-weight:bold; background-color:' + $(this).attr('member_color') + '" class="draggable" data-event=\'{"title":"' + $(this).attr('member_name') + '", "color":"' + $(this).attr('member_color') + '"}\'>' + $(this).attr('member_name') + '</div>');
            });
        },
        error: function() {
            alert("There was an error fetching events!")
        }
});

div是可选择的,颜色和文字是正确的,但它们不可拖动。我检查了class属性设置是否正确但我无法拖动日历上的项目。 有谁知道为什么他们不可拖动?最初显示时,它们是可拖动的。

1 个答案:

答案 0 :(得分:0)

是的,你需要再次绑定这个库,因为jQuery只绑定到存在的元素。我在这里回复了 - https://example.com/

你需要使用相同的代码,但我认为你不应该使用:

 $('div').remove('.draggable');

您应该更改此选项以选择特定容器,因为现在您删除了页面中所有div的可拖动

 $('#selectList > div').remove('.draggable');