0

I have the following partial view, which lists users in a table. Each row has an Enroll button, which enrolls the user to the selected course.

I need almost the same view for another task. However, I need to add users to Discussions (instead of enrolling them to a course). I know I can create another view and change the Enroll buttons to Add buttons.

However, I wonder if there is a more effective way of doing this. My approach does not seem to be easy to maintain.

@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>
renakre
  • 8,001
  • 5
  • 46
  • 99

1 Answers1

0

One way to do it is by setting an attribute of your calling action method that will render this view

<table class="table-condensed" style="font-size:smaller" data-module="@ViewData["module"]"></table>

and then use it in your JS code

<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
    }


})

For example on home page you have links like

   @Html.ActionLink("enrollment", "Index", new { module = "enroll" })
   @Html.ActionLink("Discussion", "Index", new { module = "discussion" })

and your ApplicationUserController has index action like this

public ActionResult Index(string module)
{
    ViewData["module"] = module;

    return View();
}

However if scope of project or requirements can change for enrollment and/or discussion then better to keep then separate to avoid complexity of code in single page as well as in single JS code.

Nasir
  • 207
  • 4
  • 17
  • thanks for the answer. Where does @ViewData["module"] come from? Can you elaborate in your answer? – renakre Feb 29 '16 at 13:38