模型未在表单提交中获得分配的值

时间:2019-05-29 12:55:19

标签: c# html .net asp.net-mvc model-view-controller

我是MVC的新手,我的控制器中具有以下ActionMethod:

 public async Task<ActionResult> ViewSsoProviders(int? page, string nameFilter = "", string bpIdFilter = "",
        string protocolFilter = "")

我正在尝试通过以下形式调用它:

@{
using (Html.BeginForm("ViewSsoProviders", "SsoAdmin", new
{
    page = 1,
    nameFilter = Model.ProviderNameFilter,
    bpIdfilter = Model.BusinessPartnerIdFilter,
    protocolFilter = Model.ProtocolFilterSelection
}))
{
    <div id="providerForm">
        @Html.ValidationSummary()
        <div class="form-group row">
            <span class="col-sm-4">
                @Html.LabelFor(m => m.ProviderNameFilter)
                @Html.TextBoxFor(m => m.ProviderNameFilter, new {@class = "form-control"})
            </span>
            <span class="col-sm-4">
                @Html.LabelFor(m => m.BusinessPartnerIdFilter)
                @Html.TextBoxFor(m => m.BusinessPartnerIdFilter, new {@class = "form-control", style = "display: block"})
            </span>
            <span class="col-sm-4">
                @Html.LabelFor(m => m.ProtocolFilterOptions)
                @Html.TranslatedDropDownListFor(m => m.ProtocolFilterSelection, Model.ProtocolFilterOptions, new {id = "ddlProtocols", @class = "form-control"})
            </span>
        </div>
        <button class="btn" type="submit" value="Filter">@Html.Translate("Filter")</button>
    </div>

该方法被执行,但是,尚未为过滤器分配值,我可以对'page'变量进行硬编码,它将以正确的值到达我的控制器,因此问题不在于路由本身。为什么我的路由变量无法分配值,这有什么明显的原因吗?

编辑:值得注意的是,如果我改为传递“ null”而不是视图中的任何routevalue,则可以仅将表单上分配了数据的字段传递给控制器​​。

1 个答案:

答案 0 :(得分:0)

您要提交的表格应该是帖子。您应该有一个新方法,并用以下方法装饰它:

[HttpPost]

,并使用另一个需要保存属性的模型或视图模型对其进行参数化。

例如。

[HttpPost]
public ActionResult ViewSsoProviders(MyViewModel model)
{
     //Do a redirection to ViewSoProviders
     //ex.
     return RedirectToAction("ViewSsoProviders", new {nameFilter = model.NameFiler, bpIdFilter = model.BpIdFilter, protocolFilter= model.ProtocolFilter });
}

并在剃须刀视图上指定form方法:

Html.BeginForm("ViewSsoProviders", "SsoAdmin", FormMethod.Post, new
{
    page = 1,
    nameFilter = Model.ProviderNameFilter,
    bpIdfilter = Model.BusinessPartnerIdFilter,
    protocolFilter = Model.ProtocolFilterSelection
}))