@using (Html.BeginForm())
{
<p>ID: @Html.TextBoxFor(a => a.user_id)</p>
<p>Name: @Html.TextBoxFor(a => a.user_name)</p>
<input type="submit" />
}
This is my code. I have to check null value when person click submit button. If person input null, Web will show alert.
And I tried to give id to hteml.textboxfor().
<p>ID: @Html.TextBoxFor(a => a.user_id, new {id= "user_id"})</p>
I'm not sure if this code is right. Please let me know.
CodePudding user response:
@Html.TextBoxFor will automatically generate id user_id.
And you can do it like below:
@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>
Update:
<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>
