【问题标题】:Call controller Action with empty/null strings as parameter使用空/空字符串作为参数调用控制器操作
【发布时间】:2020-09-07 14:04:06
【问题描述】:

我的控制器中有一个动作,它需要 2-3 个参数,如下所示。

public ActionResult MyAction(string str1, string str2, string str3)
{
     // code here 
}

使用一些有效值调用此操作,因为参数和结果会显示在视图中。现在我想再次调用相同的操作,并希望将空/空字符串值作为参数传递。但是当我这样调用动作时:

@Html.ActionLink("Click", "MyAction", "MyController") 

路由模板如下:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default",
        "{str1}/{str2}/{str3}",
        new {controller = "MyController", action = "MyAction", str1 = UrlParameter.Optional, str2 = UrlParameter.Optional, str3 = UrlParameter.Optional}
    );
}

我得到了与参数相同的值,如何以空/空值作为参数调用动作?

【问题讨论】:

  • “与参数相同的值”是什么意思? @Html.ActionLink("Click", "MyAction", "MyController") 应该调用带有 null 参数值的操作方法
  • @RajdeepDebnath 我的意思是当第一次调用此操作时,我得到与参数相同的值,当再次调用该操作时,我再次得到相同的值。

标签: c# asp.net-mvc asp.net-core


【解决方案1】:

试试这个代码

@Html.ActionLink("Click", "MyAction", "MyController", new { str1 = "", str2 = "" , str3 = "" }) 

【讨论】:

  • 我已经按照你的建议使用了,但我仍然得到了价值:(
  • 您获得的价值是多少,例如 str1
  • 和第一次调用action方法的值一样
  • 你试过清除缓存吗?或使用其他浏览器。
【解决方案2】:

这里可以使用 C# 可选参数

public ActionResult MyAction(string str1="", string str2="", string str3=null)
{
     // code here 
}
@Html.ActionLink("link", "About", "Home")

public ActionResult MyAction(string str1="", string str2="", string str3=null)
{
    //values
     str1=="";
     str2=="";
     str3==null;
}
@Html.ActionLink("link", "About", "Home", new { str1="a", str2="b", str3="c" })

public ActionResult MyAction(string str1="", string str2="", string str3=null)
{
    //values
     str1=="a";
     str2=="b";
     str3=="c";
}

【讨论】:

  • 我已经按照你的建议使用了,但我仍然得到了价值:(
猜你喜欢
  • 2010-11-27
  • 2014-02-21
  • 1970-01-01
  • 2016-05-12
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
相关资源
最近更新 更多