【发布时间】:2015-04-22 10:57:51
【问题描述】:
我已成功地将 Contoso University ASP.NET MVC 项目集成到我的 VS 解决方案中。我想添加某种事件处理功能,我可以在索引页面上选择一个或多个项目,例如,点击一个按钮并根据用户选择从数据库中检索某种数据。现在,我想知道在我点击页面上的按钮后如何检索用户选择的项目。在我们与数据库交互之前。
如何为每个项目添加正确的单选按钮,以便正确捕获所选项目?
现在我为每个项目添加了@Html.RadioButton()。但是,我不知道该放什么作为参数?
如何添加一个按钮来检索选定的数据? 我应该将我的事件处理逻辑放在哪里以及放置什么来检索已选择的项目?
Views/Course/Index.cshtml
@model IEnumerable<ContosoUniversity.Models.Course>
@{
ViewBag.Title = "Courses";
}
<h2>Courses</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm())
{
<p>
Select Department: @Html.DropDownList("SelectedDepartment", "All")
<input type="submit" value="Filter" />
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.CourseID)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Credits)
</th>
<th>
Department
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.RadioButton(courseRadio, )
</td>
<td>
@Html.DisplayFor(modelItem => item.CourseID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Credits)
</td>
<td>
@Html.DisplayFor(modelItem => item.Department.Name)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.CourseID }) |
@Html.ActionLink("Details", "Details", new { id = item.CourseID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.CourseID })
</td>
</tr>
}
</table>
}
CourseController.cs:
....
public ActionResult Index(int? SelectedDepartment)
{
var departments = db.Departments.OrderBy(q => q.Name).ToList();
ViewBag.SelectedDepartment = new SelectList(departments, "DepartmentID", "Name", SelectedDepartment);
int departmentID = SelectedDepartment.GetValueOrDefault();
IQueryable<Course> courses = db.Courses
.Where(c => !SelectedDepartment.HasValue || c.DepartmentID == departmentID)
.OrderBy(d => d.CourseID)
.Include(d => d.Department);
var sql = courses.ToString();
return View(courses.ToList());
}
...
【问题讨论】:
-
@Html.RadioButton() 和@Html.RadioButtonFor() 在使用和行为上有什么区别?
-
RadioButtonFor()与模型属性绑定,而RadioButton()则没有 -
@jerryh91 在名为 Selected 的模型中添加
bool属性并使用RadioButtonFor() -
你能解释一下“与模型属性绑定”是什么意思吗?
标签: c# jquery asp.net asp.net-mvc asp.net-mvc-4