【问题标题】:How to make optional parameter value in ActionResult method in Asp.Net MVC?如何在 Asp.Net MVC 的 ActionResult 方法中设置可选参数值?
【发布时间】:2019-05-28 22:34:13
【问题描述】:

当用户点击按钮时,它会重定向到另一个控制器动作方法有或没有参数值

<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();
    }

【问题讨论】:

  • 如果你使用 c# 4 或更高版本,你可以使用可选参数,只需声明参数并给出类似 yourController(int param1 = 0) 的值,那么你将能够发送或不发送这个参数
  • @AntonioAvndañoDuran 就我而言,我使用的是字符串。我已经看到整数了。它没有显示整数错误。但不适用于字符串变量
  • 如果您更新示例代码和问题以询问字符串解决方案,可能会有用

标签: asp.net-mvc model-view-controller asp.net-mvc-5 actionresult


【解决方案1】:

如果你使用的是 c# 4.0 或更高版本,你可以使用这个:

public ActionResult Details(string name = "xxx")
  {
    // some code ...
    return View();
  }

【讨论】:

    【解决方案2】:

    或者你可以使用这个带有空值的初始化参数,

    `

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

    `

    【讨论】:

      【解决方案3】:

      由于字符串本身可以为空,因此您可以在参数中使用它并且它是可选的,那么您将只检查其中的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();
      }
      

      【讨论】:

        猜你喜欢
        • 2013-12-17
        • 1970-01-01
        • 2017-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多