MVC4 - 使用Ajax

时间:2015-10-13 17:03:51

标签: c# jquery ajax asp.net-mvc-4 cascadingdropdown

使用MVC4,我正在尝试将级联列表框实现到我的一个视图中,我一直关注this tutorial并已成功创建了2个级联下拉框,但我现在需要相同类型的功能列表框,用户可以在其中选择多个项目。

只是为了澄清用户可以从下拉列表中选择威胁。

选择威胁后,将使用所选威胁的关联安全事件填充列表框,此处用户可以选择多个安全事件或单个安全事件

选择所选安全事件后,将使用与所选安全事件关联的任何控件填充另一个列表框。

这是我到目前为止所拥有的

查看模型

 public class AddNewRiskVM
    {
        public SelectList RiskTypeList { get; set; }
        public SelectList GroupMembersList { get; set; }
        public SelectList ThreatsList { get; set; }
        public SelectList SecurityEventsList { get; set; }
        public List<int> SelectedSecurityEventsIDs { get; set; }
        public SelectList ISOControlList { get; set; }
        public List<int> AssociatedIsoIDs { get; set; }
        public int ISOControlID { get; set; }

        public AddNewRiskVM()
        {
            SelectedSecurityEventsIDs = new List<int>();
            AssociatedIsoIDs  = new List<int>();
        }       
    }

控制器

public void ConfigureNewRisk(AddNewRiskVM ViewModel)
        { 
            var RiskTypes = _DBContext.RiskTypes;
            var Threats = _DBContext.Threats;

            ViewModel.RiskTypeList = new SelectList(RiskTypes, "ID", "Description");
            ViewModel.GroupMembersList = new SelectList(new List<GroupMember>(), "ID", "Name");
            ViewModel.ThreatsList = new SelectList(Threats, "ID", "Description");
            ViewModel.SecurityEventsList = new SelectList(new List<SecurityEvent>(), "ID", "Description");
            ViewModel.ISOControlList = new SelectList(new List<ISOControl>(), "ID", "Description");
        }

        public ActionResult AddNewRisk()
        {
            AddNewRiskVM ViewModel = new AddNewRiskVM();
            ConfigureNewRisk(ViewModel);

            return View(ViewModel);
        }
     public IEnumerable<ISOControl> GetISOControls(int SecurityEventID)
        {
            var QueryResults = _DBContext
                                   .SecurityEventHasISOControls
                                   .Include("SecurityEventHasISOControls.ISOControlID")
                                   .Where(x => x.SecurityEventID == SecurityEventID)
                                   .Select(x => x.ISOControl);

            return QueryResults;
        }

        public JsonResult GetJsonISOControl(int ID)
        {
            var ISOControlListT = this.GetISOControls(Convert.ToInt32(ID));
            var ISOControlList = ISOControlListT.Select(x => new SelectListItem()
            {
                Text = x.Description,
                Value = x.ID.ToString(),
            });
            return Json(ISOControlList, JsonRequestBehavior.AllowGet);
        }

注意 - 我有类似GetISOControl&amp; amp;的方法。 GetJsonControl用于SecurityEvent

查看

<div class="containeSelect">
     @using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post, new { @id = "AddNewWithSelect" }))
     {
        <h3>Add New Risk</h3>
        <fieldset>

             @Html.DropDownList("RiskType", Model.RiskTypeList, "Select Risk Type", htmlAttributes: new { @class = "CascadeInputBox", onchange = "GetMembers()"})
             @Html.DropDownList("GroupMember", Model.GroupMembersList, "Select Group Member", htmlAttributes: new {@class = "CascadeInputBox", @id = "CascadeDropDownList2"})
             @Html.DropDownList("Threats", Model.ThreatsList, "Select Threat", htmlAttributes: new { @class = "CascadeInputBox", onchange = "GetSecurityEvents()"})
             @Html.ListBoxFor(m => m.SelectedSecurityEventsIDs, Model.SecurityEventsList, htmlAttributes: new { @id = "SelectListEvent", onchange = "GetISOControls()"})
             @Html.ListBox("ISOControls", Model.ISOControlList, htmlAttributes: new { @id = "SelectListISO"})

        </fieldset>
     }

<script>
    function GetISOControls() {
        $.ajax({
            url: "@Url.Action("GetJsonISOControl", "RiskAssesment")",
            dataType: "json",
            type: "GET",
            data: { id: $("#Events").val() },
            error: function () {
            },
            beforeSend: function () {
            },
            success: function (data) {
                var items = "";
                $.each(data, function (i, item) {
                    items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
                });
                $("#SelectListISO").html(items);
            }
        });
    }
 </script>
<script>  
    function GetSecurityEvents() {
        $.ajax({  
            url: "@Url.Action("GetJsonSecurityEvent", "RiskAssesment")", 
            dataType: "json",  
            type: "GET",  
            data: { id: $("#Threats").val() },
            error: function () {  
            },  
            beforeSend: function () {  
            },  
            success: function (data) {  
                var items = "";  
                $.each(data, function (i, item) {  
                    items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";  
                });
               $("#SelectListEvent").html(items);
            }  
        });         
    }  
 </script> 

这是我第一次使用ajax,我知道我必须以某种方式更改下面的行,因为在我的帮助方法中我没有使用字符串名称,而是使用了linq表达式,也许这就是全部这是必须的,现在我什么都看不到,但可能会遗漏一些东西?

data: { id: $("#Events").val() },

如果有人可以提供任何建议,特别是对于ajax,我们将不胜感激。

提前致谢

1 个答案:

答案 0 :(得分:1)

您没有id="Events"的元素。您引用的列表框包含id="SelectedSecurityEventIDs"。因为它的<select multiple>值是一个数组,所以你需要jQuery.param方法来序列化你的数据。我推荐使用Unobtrusive Javascript,而不是用行为污染您的标记,以便{/ 1}}脚本替换为

GetISOControls

控制器方法需要

var isoList = $("#SelectListISO"); // cache it
$('#SelectedSecurityEventIDs').change(function() {
    // create a serialized representation of the selected values
    var data = $.param({ id: $(this).val() }, true);

    $.ajax({
        url: "@Url.Action("GetJsonISOControl", "RiskAssesment")",
        dataType: "json",
        type: "GET",
        data: data,
        success: function (data) {
            isoList.empty();
            $.each(data, function (i, item) {
                isoList.append($('<option></option>').val(item.Value).text(item.Text));
            });
        }
    });
});

因为您要发布一系列值(您需要调整查询以适应)。另请注意,不需要创建public JsonResult GetJsonISOControl(IEnumerable<int> ID) (它只是向客户端发送未使用的额外数据)。应该只是

SelectList

旁注:

var ISOControlList = ISOControlListT.Select(x => new
{
    Text = x.Description,
    Value = x.ID.ToString(),
});

正在创建一个与您的模型没有关系的控件(它没有名为@Html.ListBox("ISOControls", Model.ISOControlList, ..) 的属性,因此不会绑定到您的模型。我认为它应该是

ISOControls