使用Guid作为可选参数,'参数需要类型'System.Nullable'的值

时间:2015-07-21 18:51:14

标签: c# visual-studio mvvm controller

我只是帮助将我的模型链接到此控制器中的viewmodel - 这似乎有效。这是代码:

public ActionResult TechSearchKnowledgebase([Optional]Guid? createdById, [Optional]Guid? categoryId, [Optional]Guid? typeId)
        {

            var model = db.Knowledgebases.AsQueryable();

            if (createdById != Guid.Empty)
            {
                model = model.Where(k => k.CreatedById == createdById);
                ViewBag.CreatedBy = db.Users.Where(c => c.UserId == createdById).First().FullName;
            }
            if (categoryId != Guid.Empty)
            {
                model = model.Where(k => k.CategoryId == categoryId);
                ViewBag.Category = db.Categories.Where(c => c.CategoryId == categoryId).First().CategoryName;
            }
            if (typeId != Guid.Empty)
            {
                model = model.Where(k => k.TypeId == typeId);
                ViewBag.Category = db.Roles.Where(c => c.RoleID == typeId).First().RoleDescription;
            }
            model=model.OrderBy(k => k.CreatedDate);

            List<KnowledgebaseResult> knowledgebaseResults = Mapper.Map<List<KnowledgebaseResult>>(model.ToList());

            return View("TechKnowledgebaseList", knowledgebaseResults);

        }

我的代码有问题:

如果我加载它我会收到此错误:

  

参数字典包含参数的无效条目   方法'System.Web.Mvc.ActionResult'的'categoryId'   TechSearchKnowledgebase(System.Nullable 1[System.Guid], System.Nullable 1 [System.Guid],System.Nullable 1[System.Guid])' in 'HelpDesk.WebUI.Controllers.KnowledgebaseController'. The dictionary contains a value of type 'System.Reflection.Missing', but the parameter requires a value of type 'System.Nullable 1 [System.Guid]'。   参数名称:参数

1 个答案:

答案 0 :(得分:-1)

我不熟悉用于在TechSearchKnowledgebase方法中声明可选参数的语法。根据您要执行的操作,请尝试以下操作之一:

1)删除[可选]标签。您的方法将如下所示:

TechSearchKnowledgebase(Guid? createdById, Guid? categoryId, Guid? typeId)

这些现在是可以为空的Guid参数,您可以将此方法称为TechSearchKnowledgebase(null, null, null);这是否符合您的需求?

2)如果您确实需要可选参数,请查看Named and Optional Arguments。您可以在其中看到可选参数都是在所需参数之后声明的,并且它们都具有指定的默认值。由于您使用的是Guids,我猜您不希望这些真正成为可选参数,或者您希望将Guid.Empty指定为默认值。如果后者为真,那么您的方法定义将如下所示:

public ActionResult TechSearchKnowledgebase(Guid? createdById = Guid.Empty, Guid? categoryId = Guid.Empty, Guid? typeId = Guid.Empty)

如果我误解了您的问题,请澄清并提供您称之为此方法的代码。