【发布时间】:2026-02-19 22:40:02
【问题描述】:
我是 .NET 和一般 Web 开发的新手。我创建了一个表单来收集用户的评论和/或文件附件。一切正常,但我想添加客户端验证,但这样做时失败。使用 Chrome 的开发工具,我可以看到 javascript 已执行,但第一条语句失败说“无法读取未定义的属性值”。如果我删除 runat="server" 属性,它可以正常工作,但我无法再从后面的代码中访问数据。
那么我有哪些选项可以让 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);
}
}
}
提前致谢。
【问题讨论】:
标签: javascript c# asp.net