Form runat = server中的Javascript验证

时间:2014-10-27 19:10:51

标签: javascript c# asp.net

我是.NET和Web开发的新手。我创建了一个表单来收集用户的评论和/或文件附件。一切正常但我想添加客户端验证但是当我这样做时它会失败。使用Chrome的开发工具,我可以看到javascript已执行,但第一个语句未能说"无法读取未定义的属性值"。如果我删除了runat ="服务器"属性,它工作正常,但我无法再从后面的代码访问数据。

那么我有什么选择让javascript工作?或者我是以错误的方式保存数据?

aspx页面:

<form id="commentForm" name="commentForm" runat="server" enctype="multipart/form-data" method="post" onsubmit="return validateCommentForm()">
    <p>Add Comment</p>
    <textarea id="Comment" name="Comment" rows="4" class="with-100" runat="server" />

    <input id="FileAttachment" type="file" runat="server" />

    <input type="submit" id="SaveComment" class="red-button" value="Submit" />
</form>

的javascript:

function validateCommentForm()
{
    var x = document.commentForm.Comment.value;
    var y = document.commentForm.FileAttachment.value;
    if (x == '' && y == '')
    {
        alert("Either a commment or file must be supplied.");
        return false;
    }
}

C#:

protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == true)
            {
                if (Comment.Value.Length > 0)
                {
                    Insert.UserComment(Comment.Value);
                }

                HttpPostedFile UserFileAttachment = Request.Files[0];
                if (UserFileAttachment.ContentLength > 0)
                {
                    Insert.FileAttachment(UserFileAttachment);
                }
            }
        }

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以使用jQuery,您可以按照API中所述的名称调用表单元素。

检索值:

$("input[name='Comment']").val();

从JavaScript更新值(如果需要):

$("input[name='Comment']").val('some Comment');

您也可以使用以下jQuery通过ID(以及基于您的示例应该可行)来执行此操作:

$("#Comment").val();

所以你的最终JavaScript会是这样的:

function validateCommentForm()
{
    var x = $("#Comment").val();
    var y = $("#FileAttachment").val();
    if (x == '' && y == '')
    {
        alert("Either a commment or file must be supplied.");
        return false;
    }
}

我确实认为从文件输入框访问文件名有些奇怪。请参阅文件选择器jQuery documentation