c# - 带有可选 Guid 参数的 View 的 MVC Controller 方法

标签 c# asp.net-mvc

我正在尝试通过直接从菜单转到该 View 或通过单击将带我到同一 View 但带有参数和特定链接信息而不是看到的链接来使 MVC View 可访问一个通用页面,如果我直接去的话。

public ActionResult Roles(Guid applicationId)
    {
        if (applicationId == Guid.Empty)
        {
            return View();
        }

        var application = new ApplicationStore().ReadForId(applicationId);

        return View(application);
    }

我知道对于可选参数,你会做类似 Guid 的事情吗?在参数中,但 Visual Studio 不喜欢那样,我也不能做 Guid application = null 。有什么想法吗?

最佳答案

正如您已经提到的,将参数设为可选。

public ActionResult Roles(Guid? id) {
    if (id == null || id.Value == Guid.Empty) {
        return View();
    }

    var application = new ApplicationStore().ReadForId(id.Value);

    return View(application);
}

这也假定默认的基于约定的路由

"{controller}/{action}/{id}"

id 在路由模板中是可选的。

id = UrlParameter.Optional

例如

routes.MapRoute(
     name: "SomeName",
     url: "{controller}/{action}/{id}",
     defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
 );

关于c# - 带有可选 Guid 参数的 View 的 MVC Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53105429/

相关文章:

asp.net - 创建 "Live"ASP.NET MVC 应用程序

c# - 如何在c#中从mysql中读取和打印数据

c# - windows phone 8.1 如何制作确定的圆形进度条

c# - 使用 Asp.Net MVC 和 IIS 上传大于 3GB 的文件

c# - 如何使用ajax将枚举值传递给 Controller ​​?

javascript - 在 MVC razor 中使用 jQuery UI Datepicker 出现错误

asp.net-mvc - 带有 nHibernate.validator 的 MVC.NET 中的 xVal 不会触发客户端验证

c# - 如何将委托(delegate)传递给方法,其中委托(delegate)是非静态的?

c# - 实现命令行解释器

c# - Azure 计算模拟器上的 Web API 失败