【发布时间】:2017-04-04 08:54:48
【问题描述】:
我有一个 MVC 应用程序,在我从下拉菜单中选择值后,将执行处理 sql 的函数。下拉菜单位于:
http://localhost:9030/Courses/Index
在我做出选择后,结果是:
http://localhost:9030/Courses/getCoursesByTeachers?Teacher=(here is an ID of the element)
getCoursesByTeachers 是我控制器中的函数,它以 ID 作为参数。
函数如下:
public string getCoursesByTeachers(int Teacher)
{
string sql = "SELECT * FROM Course WHERE teacher_Id = @Teacher";
string connectionString = "Data Source=TSSKKEWKS0619;Initial Catalog=T-Timetable;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework";
//string course = "No courses are being taught by this teacher";
List<string> list = new List<string>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("Teacher", Teacher);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
list.Add(reader["name"].ToString());
}
}
finally
{
reader.Close();
}
}
if (list.Count==0)
{
list.Add("There are no courses being taught by this teacher.");
}
return string.Join(System.Environment.NewLine, list);
}
这就是我在我的 cshtml 中如何称呼它:
<h2>Courses taught by:</h2>
@using (Html.BeginForm("getCoursesByTeachers", "Courses", FormMethod.Get))
{
@Html.DropDownList("Teacher", (SelectList)ViewBag.Teacher, "Select teacher", new { onchange = @"form.submit()" }); // form.action('getCoursesByTeacher')
}
有没有办法修改它,所以结果不会显示在重定向页面上,而是显示在 URL 中的同一页面中:http://localhost:9030/Courses/Index。 (也许就像在它下面一样,我猜我必须在cshtml中以某种方式更改它,对吗?我不知道如何并且我不想在它工作时搞砸它:D所以我想我问你们)
希望问题足够清楚。感谢您的帮助。
【问题讨论】:
-
您可以使用
HttpPost属性,使用相同的Index操作方法并从那里调用getCoursesByTeachers方法返回相同的视图,或者使用接收AJAX 调用并在同一页面上呈现查询结果的部分视图(注意getCoursesByTeachers这种方式必须转换成ActionResult返回结果部分视图)。
标签: c# razor model-view-controller dropdown