0

My MVC form will not submit unless I have a value in my TextBoxFor field. I am using the TextBoxFor because I do want the value of the field stored in a model attribute. I need one of the two following solutions, either one satifies my needs. I either need, on submission of my form to be able to save the value of a regular TextBox to the model attribute or allow to submit when my TextBoxFor is empty.

Currently my code looks like this:

@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>
}

As mentioned this works fine when there is a value the TextBoxFor, however the form is not submitted if empty. Any help would be greatly appreciated.

NOTE: I tried adding an onclick even to the button but then it doesn't submit to controller.

4

1 回答 1

1

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

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

其次,使用 ? 确保您的文本框字段可以为空。像这样的 ViewModel 中的关键字

public int? MyAttribute { get; set; }

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

if(ModelState.IsValid)
{
// TODO:
}
于 2014-12-03T16:09:17.080 回答