如何用js获取@Html.Textboxfor中的值并检查null?

How can get value in @Html.Textboxfor with js and check null?

        @using (Html.BeginForm())
        {
            <p>ID: @Html.TextBoxFor(a => a.user_id)</p>
            <p>Name: @Html.TextBoxFor(a => a.user_name)</p>
            <input type="submit" />
        }

这是我的代码。当人们点击提交按钮时,我必须检查空值。如果人输入空,Web 将显示警报。

并且我尝试将 id 提供给 hteml.textboxfor()。

            <p>ID: @Html.TextBoxFor(a => a.user_id, new {id= "user_id"})</p>

我不确定这段代码是否正确。请告诉我。

@Html.TextBoxFor会自动生成iduser_id.

你可以像下面那样做:

@using (Html.BeginForm())
{
    <p>ID: @Html.TextBoxFor(a => a.user_id)</p>
    <p>Name: @Html.TextBoxFor(a => a.user_name)</p>
    <input type="submit" id="submit" />
}

@section scripts{ 
<script>
    $("#submit").on("click", function (e) {
        var id = $("#user_id").val();
        var name = $("#user_name").val();
        if (id == "" || name == "") {
            e.preventDefault();
            alert("value can't be null");
        }
    })
</script>

更新:

<script>
    document.getElementById("submit").addEventListener("click", function (event) {
        var id = document.getElementById("user_id").value;
        var name = document.getElementById("user_name").value;
        if (id == "" || name == "") {
            event.preventDefault();
            alert("value can't be null");
        }
    });
</script>