无法理解为什么我得到System.ArgumentNullException未被用户代码处理

时间:2013-07-20 16:06:36

标签: asp.net-mvc

我有以下Action方法: -

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult AssignGroup(int SecurityRoleID, int[] selectedGroups, int[] currentGroups)
            {try
                {if (ModelState.IsValid)
                    {   repository.AssignGroupRole(SecurityRoleID, selectedGroups, currentGroups);
                        repository.Save();
                        if (!Request.IsAjaxRequest())
                        {
                            return RedirectToAction("AssignGroup", new { id = SecurityRoleID });
                        }
                        else if (Request.IsAjaxRequest())
                        {
                            ViewBag.Users = repository.populateAssignedGroupData(SecurityRoleID);
                            return PartialView("_AssignGroup", repository.FindAllRole(SecurityRoleID));
                        }}}

以下部分视图: -

@using (Html.BeginForm("AssignGroup", "SecurityRole", FormMethod.Post))
{

<span class="b">There are Currently @Model.Groups.Count() Group/s</span>
<table class="table table-striped table-bordered bootstrap-datatable datatable">
 <thead>
<tr>     
<th> @Html.DisplayNameFor(model => model.Groups.SingleOrDefault().Name)</th>
        <th></th>
        </tr>

        </thead>
        <tbody> 
        <tr>
        @{
                        int cnt = 0;
                        List<TMS.ViewModels.GroupAssign> groups = ViewBag.Groups;

                        foreach (var group in groups.OrderBy(a=>a.Name)) {
                            if (cnt++ % 5 == 0) {
                                @:  </tr> <tr> 
                            }
                            @: <td> 
                                <input type="checkbox" 
                                       name="selectedGroups" 
                                       value="@group.GroupId" 
        @(Html.Raw(group.IsChecked ? "checked=\"checked\"" : "")) /> 
        @:  @group.Name
        @Html.Hidden("currentGroups", group.GroupId)
                            @:</td>
                        }
                        @: </tr>
         }


        </tbody> 


         @Html.HiddenFor(model => model.SecurityRoleID)
        @Html.AntiForgeryToken()

         </table>

        <input type="submit" value="Assign Groups" class="btn btn-primary"/>}

以及以下存储库方法: -

public List<GroupAssign> populateAssignedGroupData(int SecurityRoleID)
        {
            var allGroups = AllGroup();
            var securityRole = FindAllRole(SecurityRoleID);

            var roleGroups = securityRole.Groups.Select(a => a.Name);

            var viewModel = new List<GroupAssign>();
            foreach (var group in allGroups)
            {
                viewModel.Add(new GroupAssign
                {
                    GroupId = group.GroupID,
                    Name = group.Name,
                    IsChecked = roleGroups.Contains(group.Name, StringComparer.OrdinalIgnoreCase)
                });
            }
            return viewModel;
        }

public void AssignGroupRole(int id, int[] selectedGroups, int[] currentGroups)
        {
            var roleGroups = FindRole(id).Groups;

            var securityRole = FindAllRole(id);

            foreach (var group in roleGroups.ToList())
            {
                if (currentGroups != null)
                {
                    for (int c = 0; c < currentGroups.Count(); c++)
                    {
                        if (group.GroupID == currentGroups[c])
                        {

                            securityRole.Groups.Remove(group);} }} }


            if (selectedGroups != null)
            {
                for (int i = 0; i < selectedGroups.Count(); i++)
                {
                   Group r = new Group();
                   r.GroupID = selectedGroups[i];
                   securityRole.Groups.Add(r);}}}

但是,如果我点击视图中的“分配组”按钮,我将在代码foreach (var group in groups.OrderBy(a=>a.Name))上获得以下错误:部分视图: -

  

ystem.ArgumentNullException未被用户代码
处理   HResult = -2147467261 Message = Value不能为null。参数名称:   source Source = System.Core ParamName = source StackTrace:          at System.Linq.OrderedEnumerable 2..ctor(IEnumerable 1 source,Func 2 keySelector, IComparer 1 comparer,Boolean descending)          在System.Linq.Enumerable.OrderBy [TSource,TKey](IEnumerable 1 source, Func 2 keySelector)          位于c:\ Users \ Administrator \ Documents \ Visual Studio中的ASP._Page_Views_SecurityRole__AssignGroup_cshtml.Execute()   2012 \ Projects \ TMS \ TMS \ Views \ SecurityRole_AssignGroup.cshtml:第56行          在System.Web.WebPages.WebPageBase.ExecutePageHierarchy()          在System.Web.Mvc.WebViewPage.ExecutePageHierarchy()          在System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext   pageContext,TextWriter writer,WebPageRenderingBase startPage)          在System.Web.Mvc.RazorView.RenderView(ViewContext viewContext,TextWriter writer,Object instance)          在System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext,TextWriter writer)          在System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)          在System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext   controllerContext,ActionResult actionResult)          在System.Web.Mvc.ControllerActionInvoker。&lt;&gt; c_ DisplayClass1a.b _17()          在System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter)   filter,ResultExecutingContext preContext,Func`1 continuation)
  的InnerException:

1 个答案:

答案 0 :(得分:1)

该异常表示Linq查询(groups)的源为空。您需要确保ViewBag.Groups已初始化(这不会发生在您发布的代码中的任何位置)。

您想要Model.Groups吗?