代码之家  ›  专栏  ›  技术社区  ›  Liam neesan

如何在ActionResult方法中设置可选参数值Asp.NetMVC?

  •  0
  • Liam neesan  · 技术社区  · 6 年前

    当用户单击该按钮时,它将重定向到另一个控制器操作方法,该方法包含或不包含参数值

    <button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details'" >Go to Details</button>
    
    <button type="button" onclick="location.href='http://localhost/ProjectName/Customer/Details?name=xxx'" >View Details</button>
    

    客户控制器

        public ActionResult Details()   // i don't know how to pass optional parameter value
        {
            // some code ...
            return View();
        }
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Cesar Alejandro Paliza Yuriar    6 年前

    如果您使用的是c#4.0或更高版本,则可以使用:

    public ActionResult Details(string name = "xxx")
      {
        // some code ...
        return View();
      }
    
        2
  •  0
  •   manoj soma    6 年前

    或者您可以使用此初始化参数的空值,

    `

     public ActionResult Details(string Name = string.Empty)
      {
        return View();
      }
    

    `

        3
  •  0
  •   Khaksar Weqar    6 年前

    因为字符串本身是空的,所以您可以在参数中使用它,并且它是可选的,然后您将只检查 null 价值观。例如:

    public ActionResult Details(string optionalParameter)
    {
         //Check it now for value
         if(string.IsNullOrEmpty(optionalParameter))
         {
            //some code if it is empty
         }
         else
         {
            //some code if it is not empty
         }
    
        // some code ...
        return View();
    }