提交带有空的 Razor 文本框的 MVC



我的 MVC 表单不会提交,除非我的 TextBoxFor 字段中有一个值。 我正在使用 TextBoxFor ,因为我确实希望将字段的值存储在模型属性中。 我需要以下两个解决方案之一,任何一个都能满足我的需求。 在提交表单时,我需要能够将常规文本框的值保存到模型属性,或者允许在我的 TextBoxFor 为空时提交。

目前我的代码如下所示:

@using (Ajax.BeginForm("PartialResults", "Students", new { LoadItemsOnly = true }, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "find-results" }))
{
<div class="inline-ct">
    <table>
        <tr>
            <td><span class="lbl">Name: </span></td>
            @Html.TextBoxFor(m => m.Filter, new { autofocus = "autofocus", id = "name" })
        </tr>
        <tr>
            <td><span class="lbl">@Html.DisplayNameFor(m => m.LocationID): </span></td>
            <td>@Html.DropDownListFor(m => m.LocationID, new SelectList(Model.Locations, "Key", "Value"))</td>
        </tr>
        <tr>
            <td><span class="lbl">@Html.DisplayNameFor(m => m.ADGuid): </span></td>
            <td>@Html.DropDownListFor(m => m.ADGuid, new SelectList(Model.Teachers, "Key", "Value"))</td>
        </tr>
        <tr>
            <td><span class="lbl">@Html.DisplayNameFor(m => m.ClassCode): </span></td>
            <td>@Html.DropDownListFor(m => m.ClassCode, new SelectList(Model.SchoolClasses, "Key", "Value"))</td>
        </tr>
        <tr>
            <td><button type="submit" class="btn-primary" id="btn-find">Find</button></td>
            <td></td>
        </tr>
    </table>
</div>
<div id="student-find-results" class="row">
</div>
}

如前所述,当 TextBoxFor 存在值时,这工作正常,但是如果为空,则不会提交表单。 任何帮助将不胜感激。

注意:我尝试向按钮添加单击,但随后它没有提交到控制器。

首先,检查是否没有在传递给视图的 ViewModel 对象中的字段上添加 [required] 属性:

[Required(ErrorMessage = "")]
public string MyAttribute { get; set; }

其次,确保文本框字段在 ViewModel 中使用 ? 关键字可为空,如下所示

public int? MyAttribute { get; set; }

第三,检查客户端的字段是否有 JQuery 验证。请注意,如果要禁用对所有字段的验证,可以通过删除模型状态检查来修改控制器以不测试模型状态:

if(ModelState.IsValid)
{
// TODO:
}

最新更新