这是我遇到的错误, “ System.Data.SqlClient.SqlException:'参数化查询'(@name nvarchar(5),@ course nvarchar(3),@ emailAddr nvarchar(12),@'期望未提供的参数'@mentorID' 。”
I suspect the reason for the error was due to my drop down list data not getting stored as if i have just simply used a textbox , it had work out just fine.
感谢你们的帮助,谢谢大家!
DAL
public int Create(Student student)
{
//Instantiate a SqlCommand object,supply it with an INSERT SQL statement
//which will return the auto-generated StudentID after insertion,
//and the connection object for connecting to the database.
SqlCommand cmd = new SqlCommand
("INSERT INTO Student (Name, Course," +
" EmailAddr,MentorID)" +
"OUTPUT INSERTED.StudentID "
+ "VALUES(@name, @course,"
+ "@emailAddr,@mentorID)", conn);
//Define the parameters used in SQL statement, value for each parameter
//is retrieved from respective class's property.
cmd.Parameters.AddWithValue("@name", student.Name);
cmd.Parameters.AddWithValue("@course", student.Course);
cmd.Parameters.AddWithValue("@emailAddr", student.EmailAddr);
cmd.Parameters.AddWithValue("@mentorID", student.MentorID);
//A connection to database must be opened before any operations made.
conn.Open();
//ExecuteScalar is used to retrieve the auto-generated
//StaffID after executing the INSERT SQL statement
student.StudentID = (int)cmd.ExecuteScalar();
//A connection should be closed after operations.
conn.Close();
//Return id when no error occurs.
return student.StudentID;
}
控制器 // GET:学生/创建 公共ActionResult CreateProfile() { ViewData [“ StudentList”] = studentContext.GetAllStudent(); 列出mentorList =讲者Context.GetAllLecturer(); List selectedMentorList = new List(); foreach(mentorList中的讲师m) { selectedMentorList.Add( 新的SelectListItem { 值= m.LecturerID.ToString(), 文字= m.LecturerID.ToString() }); }
ViewData["MentorList"] = selectedMentorList;
return View("CreateProfile");
}
// POST: Student/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateProfile(Student student)
{
ViewData["StudentList"] = studentContext.GetAllStudent();
student.Password = "p@55Student";
if (ModelState.IsValid)
{
student.StudentID = studentContext.Create(student);
return RedirectToAction("CreateSuccess");
}
else
{
//Input validation fails, return to the Create view
return View(student);
}
}
查看
<div>
<label asp-for="MentorID"></label>
<input type="hidden" asp-for="MentorID" />
<select asp-for="MentorID"asp-items="@ViewData["MentorList"]
as List<SelectListItem>"></select>
</div>