Issue with View ActionResult on Button Click in MVC 5

Hursh 191 Reputation points
2024-06-21T05:39:46.3533333+00:00

The following code works fine and display student enrollment records on the page. Right before the table element, I have 3 buttons to filter out records based on the button that was clicked. In the controller, I added a function "IsEnrolled". The first button "All" calls "Index" and it works fine. The second button "Enrolled" call "IsEnrolled" function and I get an error:

The view 'IsEnrolled' or its master was not found or no view engine supports the searched locations.

What do I need to do to make it to work?

@model IEnumerable<MyProject.Models.MyModel>

    @{
    ViewBag.Title = "Index";
    }

    <h2>Class Enrollment</h2>

    <form method="get" action="@Url.Action(" Index")">
        <p>
            Search by Last Name: <input type="text" name="searchString" value="@ViewData[" CurrentFilter"]" />
            <input type="submit" value="Search" class="btn btn-default" /> @*| <a asp-action="Index">Go Back</a>*@
            @Html.ActionLink("Show All", "Index")
        </p>

        <div class="btn-group" role="group" aria-label="Filter by IsFeatured">
            <button type="button" class="btn btn-primary @((ViewBag.IsFeaturedFilter == null) ? " active" : "" )"
                    onclick="location.href='@Url.Action(" Index", "MyModel" )'">
                All
            </button>
            <button type="button" class="btn btn-primary @((ViewBag.IsFeaturedFilter == true) ? " active" : "" )"
                    onclick="location.href='@Url.Action(" IsEnrolled "MyModel" , new { isFeaturedFilter=true })'">
                Enrolled             
</button>             
<button type="button" class="btn btn-primary @((ViewBag.IsFeaturedFilter == false) ? " active" : "" )"
                    onclick="location.href='@Url.Action(" Index", "MyModel" , new { isFeaturedFilter=false })'">
                Not Enrolled
             </button>         </div>      </form>


    <table class="table">
        <tr style="background-color:lightsteelblue; color:navy">
            <th>
                @Html.DisplayNameFor(model => model.StudentId)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EnrollmentStatus)
            </th>
            
        </tr>

        @{
        int i = 0;
        }

        <tr class="@rowColor">
            <td>
                @Html.DisplayFor(modelItem => item.StudentID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName, new { @class = "form-control", @readonly = "readonly" })
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EnrollmentStatus)
            </td>
        </tr>
        }

    </table>

    <br />

    namespace MyProject.Controllers
    {
    public class StudentsController : Controller
    {
    private cnStudents db = new cnStudents();
    public ActionResult Index(string sortOrder, string searchString)
    {
    var subjects = from m in db.Students select m;
    ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
    ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
    switch (sortOrder)
    {
    case "name_desc":
    subjects = subjects.OrderByDescending(s => s.FirstName);
    break;
    subjects = subjects.OrderByDescending(s => s.LastName);
    break;
    case "Date":
    subjects = subjects.OrderBy(s => s.EnrollmentDate);
    break;
    }
    if (!String.IsNullOrEmpty(searchString))
    {
    if (!string.IsNullOrEmpty(searchString))
    {
    subjects = subjects.Where(s => s.LastName == searchString
    || s.FirstName.Contains(searchString)
    || s.FirstName.ToString().Contains(searchString)
    );
    }
    }
    ViewBag.CurrentSearch = searchString;
    return View(subjects);
    }
    public ActionResult IsEnrolled(bool? isFeaturedFilter = null)
    {
    var students = from m in db.Students select m;
    students = students.Where(s => s.IsEnrolled == isFeaturedFilter);
    ViewBag.IsFeaturedFilter = isFeaturedFilter; 
    return View(subjects);
    }
    public ActionResult SearchAct()
    {
    return View();
    }
    [HttpPost]
    public ActionResult SearchAct(string nameToFind)
    {
    ViewBag.SearchKey = nameToFind;
    return View();
    }
    protected override void Dispose(bool disposing)
    {
    if (disposing)
    {
    db.Dispose();
    }
    base.Dispose(disposing);
    }
    }
    }

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,345 questions
{count} votes

Accepted answer
  1. AgaveJoe 27,421 Reputation points
    2024-06-22T12:35:52.2866667+00:00

    Below is a working example using your original code with several bug fixes.

    Students Controller (with mock DbContext)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    
    namespace MvcBasic.Controllers
    {
        public class cnStudents
        {
            public cnStudents()
            {
                Students = new List<Student>() {
                    new Student()
                    {
                        StudentID = 1,
                        EnrollmentDate = DateTime.Now.AddMonths(-5),
                        FirstName = "Foo",
                        LastName = "Bar",
                        IsEnrolled = true
                    },
                    new Student()
                    {
                        StudentID = 2,
                        EnrollmentDate = DateTime.Now.AddMonths(-3),
                        FirstName = "Les",
                        LastName = "Paul",
                        IsEnrolled = false
                    },
                    new Student()
                    {
                        StudentID = 3,
                        EnrollmentDate = DateTime.Now.AddMonths(-2),
                        FirstName = "Leo",
                        LastName = "Fender",
                        IsEnrolled = true
                    },
                    new Student()
                    {
                        StudentID = 4,
                        EnrollmentDate = DateTime.Now,
                        FirstName = "Slash",
                        LastName = "",
                        IsEnrolled = false
                    }
                };     
            }
            public List<Student> Students { get; set; }
    
            public void Dispose() { }
        }
    
        public class Student
        {
            public Student() {}
            public int StudentID { get; set; }  
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public DateTime EnrollmentDate { get; set; }
            public bool IsEnrolled { get; set; }
    
        }
    
        public class StudentsController : Controller
        {
            private cnStudents db = new cnStudents();
            public ActionResult Index(string sortOrder, string searchString, bool? isFeaturedFilter = null)
            {
                var subjects = from m in db.Students select m;
                ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
                ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
                switch (sortOrder)
                {
                    case "name_desc":
                        subjects = subjects.OrderByDescending(s => s.FirstName);
                        break;
                        subjects = subjects.OrderByDescending(s => s.LastName);
                        break;
                    case "Date":
                        subjects = subjects.OrderBy(s => s.EnrollmentDate);
                        break;
                }
                if (!String.IsNullOrEmpty(searchString))
                {
                    if (!string.IsNullOrEmpty(searchString))
                    {
                        subjects = subjects.Where(s => s.LastName == searchString
                        || s.FirstName.Contains(searchString)
                        || s.FirstName.ToString().Contains(searchString)
                        );
                    }
                }
    
                if (isFeaturedFilter != null)
                {
                    subjects = subjects.Where(s => s.IsEnrolled == isFeaturedFilter);
                    ViewBag.IsFeaturedFilter = isFeaturedFilter;
                }
    
                ViewBag.CurrentSearch = searchString;
                return View(subjects);
            }
            //public ActionResult IsEnrolled(bool? isFeaturedFilter = null)
            //{
            //    var students = from m in db.Students select m;
            //    students = students.Where(s => s.IsEnrolled == isFeaturedFilter);
            //    ViewBag.IsFeaturedFilter = isFeaturedFilter;
            //    return View(subjects);
            //}
            public ActionResult SearchAct()
            {
                return View();
            }
            [HttpPost]
            public ActionResult SearchAct(string nameToFind)
            {
                ViewBag.SearchKey = nameToFind;
                return View();
            }
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
        }
    }
    
    

    Index View

    @model IEnumerable<MvcBasic.Controllers.Student>
    
    @{
        ViewBag.Title = "Index";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <h2>Index</h2>
    
    <form method="get" action="@Url.Action("Index")">
        <p>
            Search by Last Name: <input type="text" name="searchString" value="@ViewBag.CurrentSearch" />
            <input type="submit" value="Search" class="btn btn-default" /> @*| <a asp-action="Index">Go Back</a>*@
            @Html.ActionLink("Show All", "Index")
        </p>
    
        <div class="btn-group" role="group" aria-label="Filter by IsFeatured">
            <button type="button" class="btn btn-primary @((ViewBag.IsFeaturedFilter == null) ? " active" : "" )"
                    onclick="location.href='@Url.Action("Index", "Students" )'">
                All
            </button>
            <button type="button" class="btn btn-primary @((ViewBag.IsFeaturedFilter == true) ? " active" : "" )"
                    onclick="location.href='@Url.Action("Index", "Students" , new { isFeaturedFilter=true })'">
                Enrolled
            </button>
            <button type="button" class="btn btn-primary @((ViewBag.IsFeaturedFilter == false) ? " active" : "" )"
                    onclick="location.href='@Url.Action("Index", "Students" , new { isFeaturedFilter=false })'">
                Not Enrolled
            </button>
        </div>
    </form>
    
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.FirstName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.LastName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.EnrollmentDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.IsEnrolled)
            </th>
        </tr>
    
        @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.EnrollmentDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.IsEnrolled)
                </td>
            </tr>
        }
    
    </table>
    
    

3 additional answers

Sort by: Most helpful
  1. Tiny Wang-MSFT 2,171 Reputation points Microsoft Vendor
    2024-06-21T07:52:25.01+00:00

    Hi @Hursh, Let's my codes below. When I click the radio buttons, it will do a filter and update the table. You can change the radio button value and change the filter logic based on your business.

    User's image

    User's image

    @model WebAppDefIdentity.Models.MovieGenreViewModel
    @{
        ViewData["Title"] = "Index";
    }
    <h1>Index</h1>
    <form asp-controller="Movies" asp-action="Index" method="get">
        <p>
            Title: <input type="text" asp-for="SearchString" />  
            Gender:
            <span class="col-md-10">
                <span style="margin-left:10px;">
                    @Html.RadioButtonFor(model => model.IsEnrolled, "Yes") Enrolled
                </span>
                <span style="margin-left:10px;">
                    @Html.RadioButtonFor(model => model.IsEnrolled, "No") Not Enrolled
                </span>
                <span style="margin-left:10px;">
                    @Html.RadioButtonFor(model => model.IsEnrolled, "All") All
                </span>
            </span>
            <input type="submit" value="Filter" />
        </p>
    </form>
    <div id ="tbContent">
        @await Html.PartialAsync("_MovieTable", Model.Movies)
    </div>
    @section Scripts{
        <script>
            $('input[type="radio"]').on('change', function (e) {
                $.ajax({
                    url: "/movies/GetTable?isEnrolled=" + e.target.value,
                    type:'get',
                    success: function (data) { 
                        $("#tbContent").html(data);
                    }
                })
            });
        </script>
    }
    
    
    public async Task<IActionResult> Index(string searchString, string isEnrolled)
    {
        var movies = from m in _context.Movie
                     select m;
        if (!string.IsNullOrEmpty(searchString))
        {
            movies = movies.Where(s => s.Title!.Contains(searchString));
        }
        if (!string.IsNullOrEmpty(isEnrolled))
        {
            movies = movies.Where(x => x.Genre == "asdf");
        }
        var movieGenreVM = new MovieGenreViewModel
        {
            Genres = new SelectList(await genreQuery.Distinct().ToListAsync()),
            Movies = await movies.ToListAsync(),
            IsEnrolled = string.IsNullOrEmpty(isEnrolled) ? "All" : isEnrolled
        };
        return View(movieGenreVM);
    }
    
    public async Task<PartialViewResult> GetTable(string isEnrolled)
    {
        var movies = from m in _context.Movie
                     select m;
        if (isEnrolled == "Yes")
        {
            movies = movies.Where(x => x.Genre == "asdf");
        }
        return PartialView("_MovieTable", await movies.ToListAsync());
    }
    
    
    

    And this is my partial view.

    @model IEnumerable<WebAppDefIdentity.Models.Movie>
    <table class="table">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.Title)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.ReleaseDate)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Genre)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.Price)
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Title)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ReleaseDate)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Genre)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Price)
                    </td>
                </tr>
            }
        </tbody>
    </table>
    
    
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Tiny


  2. Hursh 191 Reputation points
    2024-06-21T18:54:46.52+00:00

    It did not resolve the issue.

    I used @model IEnumerable<MyProject.Models.MyModel> which works for .ForDisplay but did not work for .RadioButtonFor

    But you are using @model WebAppDefIdentity.Models.MovieGenreViewModel, it gives me an error

    The type or namespace name 'Routing' does not exist in the namespace 'System.Web' in mvc

    0 comments No comments

  3. AgaveJoe 27,421 Reputation points
    2024-06-21T19:32:20.7533333+00:00

    The URL action in your original code has syntax errors. It is has an extra space and it is missing a comma and double quote. It should be...

    @Url.Action("IsEnrolled", "MyModel", new { isFeaturedFilter=true })
    

    Although the controller you share is "Students" so I think it should actually be...

    @Url.Action("IsEnrolled", "Students", new { isFeaturedFilter=true })
    

    Tiny Wang-MSFT, was simply trying to show you a better approach of using radio buttons to filter a results set. The code came from a tutorial on this site. I'm sure Tiny thought you understood this.

    The tutorial is pretty good and covers filtering data and general MVC coding patterns. You might want to give it a try yourself.

    https://video2.skills-academy.com/en-us/aspnet/mvc/overview/getting-started/introduction/