这是我的挑战。我已经成功创建了一个表单,当用户填写并提交时,他/她会在他们的电子邮件收件箱中收到一条成功消息。但是现在我面临的挑战是,每当触发“提交”按钮时,即使没有将数据插入数据库,它们仍然会收到成功消息。我不知道自己在编码中出了什么问题。请帮忙。这是我的C#代码:
public bool InsertRegistration()
{
// Determine the currently logged on user's UserId
MembershipUser currentUser = Membership.GetUser();
Guid currentUserId = (Guid)currentUser.ProviderUserKey;
//Start of Upload 1
FileUpload img = (FileUpload)AdmissionUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File1 = AdmissionUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File1.ContentLength];
//Get content type
string contenttype = File1.ContentType;
//Get file name
string filename = Path.GetFileName(File1.FileName);
//force the control to load data in array
File1.InputStream.Read(imgByte, 0, File1.ContentLength);
}
FileUpload img1 = (FileUpload)StudentIDUpload;
Byte[] imgByte1 = null;
if (img1.HasFile && img1.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File2 = StudentIDUpload.PostedFile;
//Create byte Array with file len
imgByte1 = new Byte[File2.ContentLength];
//Get content type
string contenttype1 = File2.ContentType;
//Get file name
string filename1 = Path.GetFileName(File2.FileName);
//force the control to load data in array
File2.InputStream.Read(imgByte1, 0, File2.ContentLength);
}
FileUpload img2 = (FileUpload)TranscriptUpload;
Byte[] imgByte2 = null;
if (img2.HasFile && img2.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File3 = TranscriptUpload.PostedFile;
//Create byte Array with file len
imgByte2 = new Byte[File3.ContentLength];
//Get content type
string contenttype2 = File3.ContentType;
//Get file name
string filename2 = Path.GetFileName(File3.FileName);
//force the control to load data in array
File3.InputStream.Read(imgByte2, 0, File3.ContentLength);
}
FileUpload img3 = (FileUpload)PassportUpload;
Byte[] imgByte3 = null;
if (img3.HasFile && img3.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File4 = TranscriptUpload.PostedFile;
//Create byte Array with file len
imgByte3 = new Byte[File4.ContentLength];
//Get content type
string contenttype3 = File4.ContentType;
//Get file name
string filename3 = Path.GetFileName(File4.FileName);
//force the control to load data in array
File4.InputStream.Read(imgByte3, 0, File4.ContentLength);
}
//SqlDateTime sqldatenull;
using (var con = new SqlConnection(conStr))
{
using (var com = new SqlCommand("INSERT INTO Candidates(FirstName, MiddleName, Surname, DateOfBirth, Phone, Email, DateApplied, CurrentLevel, MatricNo, JAMBNo, UTMEScore, YearOfAdmission, ExpectedYearOfGraduation, NIN, StudyMode, EntryMode, NextOfKin, NextOfKinEmail, NextOfKinPhone, RelationToNextOfKin, AcademicReferee, AcademicRefereeMobile, RelationWithAcademicReferee, DirectEntryRegNo, DirectEntryGrade, CurrentGPA, Courseid, Institution, HeadOfDept, HODPhone, HODEmail, RelatedToGovtOfficial, GovtOfficialName, PositionOfGovtOfficial, OnScholarship, ScholarshipName, YearOfScholarship, StateID, LGID, Community, AccountNo, SortCode, UType, AdmissionLetter, AdmissionLetterFileName, AdmissionImageType, StudentID, StudentIDFileName, StudentImageType, Transcript, TranscriptFileName, TranscriptImageType, Passport, PassportFileName, PassportImageType, Maths, Eng, Subject3, Subject4, Subject5, Subject6, Subject7, Address, FacultyID, GradeSubject3, GradeSubject4, GradeSubject5, GradeSubject6, GradeSubject7, Location, UserId, StateOfResidence, Gender, Bank) VALUES (@FirstName, @MiddleName, @Surname, @DateOfBirth, @Phone, @Email, @DateApplied, @CurrentLevel, @MatricNo, @JAMBNo, @UTMEScore, @YearOfAdmission, @ExpectedYearOfGraduation, @NIN, @StudyMode, @EntryMode, @NextOfKin, @NextOfKinEmail, @NextOfKinPhone, @RelationToNextOfKin, @AcademicReferee, @AcademicRefereeMobile, @RelationWithAcademicReferee, @DirectEntryRegNo, @DirectEntryGrade, @CurrentGPA, @Courseid, @Institution, @HeadOfDept, @HODPhone, @HODEmail, @RelatedToGovtOfficial, @GovtOfficialName, @PositionOfGovtOfficial, @OnScholarship, @ScholarshipName, @YearOfScholarship, @StateID, @LGID, @Community, @AccountNo, @SortCode, @UType, @AdmissionLetter, @AdmissionLetterFileName, @AdmissionImageType, @StudentID, @StudentIDFileName, @StudentImageType, @Transcript, @TranscriptFileName, @TranscriptImageType, @Passport, @PassportFileName, @PassportImageType, @Maths, @Eng, @Subject3, @Subject4, @Subject5, @Subject6, @Subject7, @Address, @FacultyID, @GradeSubject3, @GradeSubject4, @GradeSubject5, @GradeSubject6, @GradeSubject7, @Location, @UserId, @StateOfResidence, @Gender, @Bank"))
{
com.Connection = con;
com.Parameters.AddWithValue("@FirstName", txtFN.Text);
com.Parameters.AddWithValue("@MiddleName", txtMN.Text);
com.Parameters.AddWithValue("@Surname", txtLN.Text);
答案 0 :(得分:1)
您要在smtpClient.Send(msg);
之前致电InsertRegistration();
,以便发送电子邮件;然后尝试将数据插入数据库中。
您可能还想从bool
返回InsertRegistration();
,如@Rahul上面建议的那样。
尽管确实关闭了连接,但不确定在何处打开连接;因此,如果您在方法中打开它,但将其包装在using
中,则可以跳过Close方法(因为使用方法会关闭它),因此:
public bool InsertRegistration()
{
// ...
using (var conn = new SqlConnection(...))
{
using (var com = new SqlCommand("INSERT INTO Candidates..."))
{
com.Parameters.AddWithValue("@FirstName", txtFN.Text);
// ... etc
con.Open(); // open connection here, just before executing
// return the true/false for whether a row was inserted
return com.ExecuteNonQuery() >= 1;
}
}
}
protected void btnsendmail_Click(object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader(Server.MapPath("~/Account/RegMessage.html")))
{
// ...
if (InsertRegistration())
{
// Only run if inserted correclty
smtpClient.Send(msg);
lblMessage.Text = "Application submitted successfully! ...";
lblMessage.ForeColor = System.Drawing.Color.Green;
}
else
{
lblMessage.Text = "Error submitting application";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
lblMessage.Visible = true;
}
}
答案 1 :(得分:0)
ExecuteNonQuery
返回受影响的行数,因此您可以更改方法签名以返回相同的结果
public int InsertRegistration() {
// all code
int rows = com.ExecuteNonQuery();
return rows;
}
因此在事件处理程序中进行检查,然后显示类似消息
int rows = InsertRegistration();
if(rows > 0) {
lblMessage.Visible = true;
lblMessage.Text = "Application submitted successfully! C...";
}
答案 2 :(得分:0)
首先,我建议使用模式“异步任务”来避免应用程序内出现脱钩。 (请参见下面的示例)
第二,如Ben所说,使用劳尔在他的答案中的逻辑将您的方法返回为布尔值:
因此,请尝试以下操作:
public async Task<bool> InsertRegistration()
{
// all code
int rows = await com.ExecuteNonQueryAsync();
if(rows>0)
{
return true;
}
else
{
return false;
}
}
protected void btnsendmail_Click(object sender, EventArgs e)
{
using (StreamReader reader = new
StreamReader(Server.MapPath("~/Account/RegMessage.html")))
{
// ...
if (InsertRegistration())
{
// Only run if inserted correclty
smtpClient.Send(msg);
lblMessage.Text = "Application submitted successfully! ...";
lblMessage.ForeColor = System.Drawing.Color.Green;
}
else
{
lblMessage.Text = "Error submitting application";
lblMessage.ForeColor = System.Drawing.Color.Red;
}
lblMessage.Visible = true;
}
}