剃刀,两种形式,相同的领域

问题描述 投票:0回答:1

表单1是一组过滤器,“提交”按钮将这些过滤器应用于GET方法。表单2是一组数据,“提交”按钮保存该数据,并通过POST方法继续过滤。过滤器选项来回传递 - 用户获取初始页面,可能会设置一些过滤器,这些过滤器在控制器方法方面再次获得同一页面,然后用户可以修改一些数据并通过POST保存,然后返回使用GET获取相同的过滤页面。

简化(更多可能不相关):

@model PagedList.IPagedList<xxx.Models.WttPlatformGridRow>

@using (Html.BeginForm("PlatformGridEdit", "Wtt", FormMethod.Get))
{
  @Html.CheckBox("ExcludeThrough", (bool)ViewBag.ExcludeThrough)
  <input type="submit" value="Filter" />
}

@using (Html.BeginForm("PlatformGridEdit", "Wtt", FormMethod.Post))
{
  @Html.Hidden("ExcludeThrough", (bool)ViewBag.ExcludeThrough)
  <input type="submit" value="Save" />
}

简化的控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PlatformGridEdit(List<WttPlatformGridRow> rows, bool? excludeThrough)
{ etc }

public ActionResult PlatformGridEdit(bool? excludeThrough)
{ etc }

显然,在HTML中命名两个相同的元素是非法的,并且它无论如何都不起作用(参数在C#方法中为null)。

到目前为止我看到的答案建议使用所有数据的单个BeginForm。精细。除了一个是GET(没有数据更改),一个是POST(数据更改)。用户需要能够为过滤器添加书签,因此无论如何我都无法将其全部作为POST处理,否则浏览器会询问用户重新提交表单数据是否正常。

我也使用IPagedList(据我所知)排除了使用带有列表字段的单个模型而不是使用ViewBag。

另一种选择似乎是使用客户端脚本将值从一个字段复制到另一个字段。但是,当控制器方法中的参数名对于两个客户端字段都相同时,我看不到如何执行此操作。

请问最好的处理方法是什么?

html razor .net-4.5
1个回答
0
投票

我有一个解决方案,但我不禁想到必须有一个更好的方法。

FWIW,这就是我所做的。这两个字段具有不同的名称(但相似)。 “主”版本(可见复选框)具有在提交时将值复制到“从”版本(隐藏字段)的脚本。控制器方法接受两个名称并决定哪些是相关的 - 一个或两个应该为null,但两者都不应该有值,但我们处理它以防万一。

最后,控制器返回具有组合值的视图(使用“主”标识)。

查看 - 表单1:

bool excludeThrough = ViewBag.ExcludeThrough != null ? ViewBag.ExcludeThrough : false;

@Html.CheckBox("ExcludeThrough", excludeThrough, new
{
    @class = "form-control",
    onchange = "document.getElementById('ExcludeThroughFilter').value = document.getElementById('ExcludeThrough').value;"
})

查看 - 表单2:

@Html.Hidden("ExcludeThroughFilter", excludeThrough)

控制器:

public ActionResult PlatformGridEdit(..., bool? excludeThrough, bool? excludeThroughFilter)
{
    bool excThru = false;
    if (excludeThrough.HasValue) excThru = excludeThrough.Value;
    if (excludeThroughFilter.HasValue && excludeThroughFilter.Value) excThru = true;
    ...etc...
}
© www.soinside.com 2019 - 2024. All rights reserved.