【问题标题】:Why are the optional query parameters appearing in child action when using Html.Action inside of a view?为什么在视图中使用 Html.Action 时子操作中会出现可选的查询参数?
【发布时间】:2014-07-31 21:20:07
【问题描述】:

在 MVC 应用程序中,我有 2 个操作方法。一个显示布局的一部分,在它的中间,它尝试呈现另一个动作(呈现项目列表)。为了方便起见,我这样做了,如果我 ajax 第一个动作,我将得到第二个动作的结果。

代码如下所示:

public ActionResult Action1(int? foo = null, int? bar = null, string search = null)
{
    ViewBag.Foo = foo;
    ViewBag.Bar = bar;
    ViewBag.Bar = search;
    if (Request.IsAjaxRequest() || this.ControllerContext.IsChildAction)
    {
        return Action2(foo, bar, search);
    }
    var model = GetSomeData();
    return View(model);
}

public ActionResult Action2(int? foo = null, int? bar = null, string search = null)
{
    ViewBag.Foo = foo;
    ViewBag.Bar = bar;
    ViewBag.Bar = search;
    var model = GetSomeOtherData(foo, bar, search);
    return View();
}

然后在 View 中查看 Action1:

@model SomeClass
<div>
    Some layout and stuff from the model goes here
    @Html.Action("Action2", new { foo = ViewBag.Foo, bar = ViewBag.Bar })
</div>

对于 Action2 的 View

@model IEnumerable<SomeOtherClass>
<div>
    <form action="@Url.Action("Action1", new { foo = ViewBag.Foo, bar = ViewBag.Bar })">
        <input type="text" name="search"/>
        <input type="submit" value="Search"/>
    </form>
    Here we render a list of items from the model
</div>

foobar 都为null 并且我ajax Action1 或仅请求Action2 时,表单中的URL 将不包含为null 的查询参数。当我正常请求 Action1 时出现问题(不是通过 ajax)。即使foobar 均为空,URL 仍包含一个查询:?foo=&amp;bar=

有人知道为什么会发生这种情况以及\或如何防止这种情况发生吗?我的意思是,如果查询参数为空,我不想添加它们。

【问题讨论】:

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


    【解决方案1】:

    那么你为什么不检查它们在 View 中是否为空?如果他们只是使用:

    @{
    var foo = ViewBag.Foo;
    var bar = ViewBag.Bar;
    }
    
    @if(foo == null && bar == null){
    
    @Html.Action("Action2","ControllerName")
    }
    

    【讨论】:

    • 您的回答让我知道了如何解决我的问题。我没有为 foo 和 bar 的所有组合创建一组 if,而是手动构建 routevaluedictionary。
    【解决方案2】:

    Andreiyfrag 的回答让我知道了如何解决我的问题。在 Action2 的视图中,我只是像这样手动构建我的 routevaouedictionary:

    var searchArguments = new Dictionary<string, object>();
    if (ViewBag.Foo != null)
    {
        searchArguments.Add("foo", ViewBag.Foo);
    }
    if (ViewBag.Bar != null)
    {
        searchArguments.Add("bar", ViewBag.Bar);
    }
    

    然后像这样使用它:

    @Url.Action("Action1", new RouteValueDictionary(searchArguments) )
    

    看来,如果我在子操作 (Url.Action) 的视图中构造一个 url,则将包含所有提供的查询参数(即使它们为空),但如果相同的操作正常运行一个(非子动作),那么 null 参数将被省略。我不知道为什么会发生这种情况,会不会是 Razor 或 MVC 中的错误?

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2013-11-13
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多