首页 > 解决方案 > 强制用户在发布前至少点击一次按钮

问题描述

我希望用户在发布表单信息之前单击一个按钮以在我的页面上添加一行。

基本上页面上有一个按钮,可以将字符串行添加到 div,我想确保他们至少单击了一次此按钮。如果他们有,他们可以成功发布,如果没有,我想显示一条错误消息,说明 div 必须至少有 1 个项目

我不知道如何解决这个问题。我应该使用jQuery吗?有没有办法做到这一点DataAnnotations

标签: c#jqueryrazormodel-view-controller

解决方案


jQuery 似乎很适合这个:

/* Lets declare a global boolean variable to hold the status of having at least one item in the div */
var rowAdded = false;

// listen for the add-row click. When clicked, toggle rowAdded.
$('button').click(function() {
    rowAdded = true;
});

// listen for the form submission and check rowAdded before sending the form.
$('#submit').click(function() {
    if(rowAdded){
        // submit the form
    } else {
        // user has not added a string row to the div, prompt them to add a row.

        // prompt method 1, use alert()
        alert('Please add a row before submitting this form.');

        // prompt method 2, print string to the dom
        var promptString = 'Please add a row before submitting this form.';
        $('#prompt-div').append('<p>' + promptString + '</p>');
    }
});

推荐阅读