剃刀,两种形式,相同的字段

时间:2019-03-20 22:25:40

标签: html razor .net-4.5

表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。

另一种选择似乎是使用客户端脚本将值从一个字段复制到另一个字段。但是当两个客户端字段的控制器方法中的参数名称相同时,我看不到该怎么做。

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

1 个答案:

答案 0 :(得分: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...
}