【问题标题】:Using Guid as an optional parameter gives 'parameter requires a value of type 'System.Nullable'使用 Guid 作为可选参数给出'参数需要'System.Nullable'类型的值
【发布时间】:2015-07-21 18:51:13
【问题描述】:

我刚刚在这个控制器中将我的模型链接到我的视图模型 - 这似乎有效。代码如下:

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.Nullable1[System.Guid], System.Nullable1[System.Guid], System.Nullable1[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.Nullable1[System.Guid]'。 参数名称:参数

【问题讨论】:

标签: c# visual-studio mvvm controller


【解决方案1】:

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

1) 移除 [Optional] 标签。您的方法将如下所示:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    相关资源
    最近更新 更多