c# - 未获取下拉列表数据
问题描述
这是我得到的错误,“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.
如果你们能提供帮助,不胜感激,非常感谢你们!!
达尔
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: Student/Create public ActionResult CreateProfile() { ViewData["StudentList"] = studentContext.GetAllStudent(); 列出导师列表=讲师上下文.GetAllLecturer(); List selectedMentorList = new List(); foreach(导师列表中的讲师 m){ selectedMentorList.Add(新 SelectListItem { Value = m.LecturerID.ToString(), Text = 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>
解决方案
推荐阅读
- amazon-web-services - 从命令行 (cli) 使用 aws ec2 describe-instances 时按标签过滤不起作用
- python-3.x - 在运行时动态创建 CFUNCTYPE
- istio - 使用更新的配置安装 Istio 不会删除 Prometheus ServiceMonitor 对象
- robotframework - 如何在 Visual Code Studio 上设置机器人框架
- java - Java ArrayDeque 中的 pop() 和 remove() 有本质区别吗?
- python - 有没有办法在代码中解决这个问题?
- python - 在 pandas 中搜索列
- javascript - 在 react js 的严格模式树中检测到如何修复旧版上下文 API
- javascript - 在模块需要期间强制传递参数
- mysql - 从另一个具有受限 IP 地址的网络连接到 MySQL 数据库