使用不同按钮的相同部分视图
问题描述:
我有以下部分视图,其中列出了表中的用户。每一行都有一个注册按钮,它将用户注册到所选课程。使用不同按钮的相同部分视图
我需要几乎相同的观点来完成另一项任务。但是,我需要将用户添加到讨论中(而不是将其注册到课程中)。我知道我可以创建另一个视图并将“注册”按钮更改为“添加”按钮。
但是,我不知道是否有更有效的方法来做到这一点。我的方法似乎不容易维护。
@model IEnumerable<ApplicationUser>
<h4>Search results:</h4>
<table class="table-condensed" style="font-size:smaller">
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
<input class="btn_Enroll" data-userid="@item.Id" value="Enroll" type="button" />
</td>
</tr>
}
</table>
<script>
$(".btn_Enroll").click(function() {
//code for enrolling
var course_id = $("#hdn_SelectedCourseId").val();
})
</script>
答
一种方式来做到这一点是通过设置调用操作方法的一个属性,它会使这个观点
<table class="table-condensed" style="font-size:smaller" data-module="@ViewData["module"]"></table>
,然后在您的JS代码中使用它
<script>
$(".btn_Enroll").click(function() {
//code for enrolling
var course_id = $("#hdn_SelectedCourseId").val();
var moduleType = $(this).closest("table").attr("data-module");
if (moduleType === "enroll")
{
//Do enrollment
}
else if (moduleType === "discussion")
{
//discuss here
}
})
例如,在主页上您有链接,如
@Html.ActionLink("enrollment", "Index", new { module = "enroll" })
@Html.ActionLink("Discussion", "Index", new { module = "discussion" })
和你ApplicationUserController具有指标作用这样
public ActionResult Index(string module)
{
ViewData["module"] = module;
return View();
}
但是,如果项目或要求的范围内可以注册和/或讨论修改,然后更好地保持,然后分开,以避免代码在单页的复杂性以及单个JS代码。
感谢您的回答。 @ViewData [“module”]来自哪里?你能否详细说明你的答案? – renakre
为了更好的可读性更新了答案 – Nasir