【问题标题】:ASP.NET if route parameter is not given then do something [closed]ASP.NET 如果没有给出路由参数,那么做一些事情[关闭]
【发布时间】:2016-01-08 01:03:01
【问题描述】:

我在 ASP.NET MVC 4 + Razor 中设置了一些带有参数的路由。

我将 {id} 的参数传递给控制器​​...然后在控制器上我要检查以下内容:

A.如果id存在于数据库中,则返回视图

B.如果没有提供id,重定向到Index

我不知道该怎么做 - 搜索并不能真正提供任何信息。

有人可以告诉我如何执行 if / else 语句来检查是否提供了 {id} 吗?

控制器:

public ActionResult View(int id)
        {
            return View();
        }

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


    【解决方案1】:

    您可以将您的方法参数设置为 nullable int 以便它适用于请求网址,例如

    yourDomainName/yourController/viewyourDomainName/yourController/view/25

    public ActionResult View(int? id)
    {
       if(id!=null)  // id came in the request
       {
          int postId= id.Value;
          var postViewModel = new PostViewModel { Id=postId};
    
          // Use postId to get your entity/View model from db and then return view
          // The below is the code to get data from Db. 
          // Read further if your data access method is different.
    
          var db = new MyDbContext()
    
          var post=db.Posts.FirstOrDefault(x=>x.Id==postId);
          if(post!=null)
          {
              postViewModel.Title = post.Title;
              return View(postViewModel);
          }
          return View("PostNotFound"); // Make sure you have this view.
       }
       //If code reaches here, that means no id value came in request.
       return RedirectToAction("Index");
    }
    

    假设 MyDbContext 是您的 DbContext 类,并且您正在使用实体框架进行数据访问。如果您的数据访问方法不同(ADO.NET/NHibernate 等),您可以使用您的数据访问代码更新该部分代码。

    【讨论】:

    • 完美运行,非常感谢!您的代码也帮助我为此添加了错误处理。 :)
    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多