表单不会在提交时执行GET

时间:2014-05-21 21:18:19

标签: html asp.net asp.net-mvc razor submit

我的模型包含:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我的控制器包含:

public ActionResult Index(int? personId)
{
    var people = db.People; // all people in my database
    ViewBag.People = new SelectList(people, "Id", "Name", personId);
    return View();
}

我的观点包含:

@using (Html.BeginForm(null, null, FormMethod.Get, new { @class = "form-inline" }))
{
    @Html.DropDownList("personId", ViewBag.People as SelectList, "All people", new { @class = "form-control select-submit" })
}

我有这条Javascript:

<script type="text/javascript">
    (function ($) {
        $(".select-submit").change(function () {
            $(this).parents("form").submit();
            alert("form submitted!");
        });

    })(jQuery);
</script>

当我从DropDownList中选择一个人时,我会看到alert弹出窗口,页面会刷新。当我选择默认选项("All People")时,我也会看到弹出窗口,但页面没有刷新。

我希望在选择默认选项时将"personId"设置为""。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

啊,我找到了。检查完html后,我注意到表单正在使用数据验证。选择一个人后会添加这些html属性:

data-val="true" data-val-number="The field Int32 must be a number." data-val-required="The Int32 field is required."

由于""Int32无效,因此无法提交表单。将此html属性添加到DropDownList解决了它:

data_val = false