【发布时间】: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>
当foo 和bar 都为null 并且我ajax Action1 或仅请求Action2 时,表单中的URL 将不包含为null 的查询参数。当我正常请求 Action1 时出现问题(不是通过 ajax)。即使foo 和bar 均为空,URL 仍包含一个查询:?foo=&bar=。
有人知道为什么会发生这种情况以及\或如何防止这种情况发生吗?我的意思是,如果查询参数为空,我不想添加它们。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4 razor