Organize a collection of objects using the MVC framework

Creating a page to display selected movies based on genre using $.post method.

If no genre is selected, all movies should be displayed as the default selection.

This is the code for the Controller:

public class BrowseController : Controller
{
    private MovieContext context = new MovieContext();
    
    // GET: Browse
    public ActionResult Index()
    {
        ViewBag.Genres = context.Genre.ToList();
        IEnumerable<Movie> mov = TempData["movies"] as IEnumerable<Movie>;
        
        if (mov == null)
        {
            IEnumerable<Movie> movies = context.Movies.ToList();
            return View(movies);
        }

        return View(mov);
    }
    
    [HttpPost]
    public ActionResult Index(int id = -1)
    {
        IEnumerable<Movie> model;
        
        if (id != -1)
        {
            model = context.Movies.Where(x => x.GenreId == id);
        }
        else
        {
            model = context.Movies.ToList();
        }
        
        ViewBag.Genres = context.Genre.ToList();
        TempData["movies"] = model;
        return RedirectToAction("", "Browse");
    }
}

This is the view code:

@model IEnumerable<Movies.Models.Movie>
@using Movies.Models
@{
ViewBag.Title = "Index";
var Movie = Model.FirstOrDefault();
List<Genre> Genres = ViewBag.Genres;
}
@Html.DropDownListFor(m => Movie.GenreId, new SelectList(Genres, "Id", 
"Name"), "")
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Rating)
    </th>
    <th>
    </th>
    <th></th>
</tr>

@foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Rating)
        </td>
        <td></td>

    </tr>
}

</table>
@section Scripts{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>


    $('select#Movie_GenreId').on('change', function () {
        var value = $(this).find(':selected').val();

        var url = "/Browse/Index";

        $.post(url, { id: value });

    });
</script>

}

After checking Chrome Debugging tool and Network tab, there are no errors shown in the Preview tab of response. The Get Browse/Index action is returning expected results but not displaying them in the View. I am unsure why this is happening.

Answer №1

Ensure you include a `callback` function in your POST request response handling to update the DOM structure.

$.post(url, { id: value },function(response){
     //handle response here
});

When using AJAX, the goal is to dynamically update the DOM without refreshing the entire page.

To achieve this, return a JSON object with all relevant information and manage it within the callback function of the $.post method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulty arises when applying hover effects to animations using callbacks

Currently facing an issue with the hover event in jQuery. There are two side-by-side containers with hover events on both. When hovering, a div containing additional information slides up into view and slides back down when the hover ends. The concept is ...

Unable to access information (TcpClient/Server)

I have successfully connected my TcpClient to my TcpServer, but I am having trouble getting them to communicate. I have tried using client.GetStream() and BinaryReader/Writer. Below is the code snippet: -Client: // Client code goes here -Server: // Se ...

What is the best way for me to make my JavaScript function return images?

I am working on a function that is supposed to display images based on whether a password check is correct or not. The image should show a cross if the passwords don't match and a tick if they do. Here is the code I have so far: <script type="text ...

Struggling to incorporate real-time data into a jQuery pie chart

Having trouble setting dynamic data into my pie chart. The hard-coded code is functioning correctly, but there seems to be an issue with the dynamic data. $(contact_listddd).each(function(index, data) { total_kra=data.graph_count; ...

Is there a way to transfer the value from one directive to another directive template and access it in a different directive's scope?

I attempted to pass the directive attribute value to a template ID, which can then be used in another directive. Below is my index.html code: <my-value name="jhon"></my-value> Here is the JavaScript code: .directive('myValue',func ...

Trouble arises when trying to invoke a prototype function using setInterval

Having created a prototype class for Bot, I encountered an issue. Upon calling the init() function after its creation, it correctly alerts "a 5000". However, when the prototype function calls getUpdates(), it fails to reach the value of "this" and instead ...

Users are reporting that verification emails are not being sent when the Accounts.createUser function is used within

I have a simple meteor method set up to create user accounts. In my server/methods.js file: Meteor.methods({ createUserAccount: function(user) { return Accounts.createUser(user); } }); Then in my server/init.js file: Meteor.startup(function() ...

How can I customize the configuration for react-mui-draft-wysiwyg?

I am currently using an HTML editor called Material UI: import MUIEditor, { MUIEditorState } from "react-mui-draft-wysiwyg"; <MUIEditor editorState={formElement.editorState} onChange={formElement.onChange} /> I am trying to cus ...

What steps can be taken to remove the search parameter responsible for the error?

Imagine having a webpage that displays search results based on the parameters in the URL, like this: https://www.someurl.com/categories/somecategory?brands=brand1,brand2,brand3 This URL will show listings for only brand1, brand2, and brand3. Additionally ...

"Using Mongo and Express to retrieve a user by their ID results in an object being null

I've been attempting to retrieve a user object by ID using User.findById. When I make the request in Postman, it returns "user": null, even though the object with the included ID contains fields. Example of my object: { "_id" : ObjectId("5b3ca ...

Ensuring Bootstrap v4 Does Not Collapse When Double-Clicked

Issue: An issue arises when utilizing a checkbox to trigger the collapse of an element. It becomes susceptible to breaking if the checkbox is double-clicked before the transition of the collapse element completes. Possible Fix: In order to avoid this pro ...

Having trouble loading an image with texture loader in Three.js? The issue may be related to the size and scale of the plane geometry

Can someone please assist me with loading images using TextureLoader? I am encountering a major issue where I am unsure how to add images to a mesh in a 1:1 scale and calculate PlaneGeometry. My goal is to display the loaded image in its original size with ...

"Implementing parallelism for both the producer and consumer using shared internal state

I am exploring a potential implementation of the producer and consumer pattern in C# .NET 4.6.1. My objective is to read files, perform calculations on the data, and save the results. Each file originates from a specific device (e.g., a data logger) and r ...

Strategies for detecting changes in multiple HTML select elements with jQuery

I currently have three select HTML tags and I would like to filter my table using the selected values (group of selected tags) with an AJAX request. For example, filtering by Gender, Location, and Season. My question is how can I achieve this without dup ...

Is the WebMethod function malfunctioning within an ASP.Net Web Role using Web Forms?

Issue Reproduction Steps: To replicate the issue, follow these steps: Open Visual Studio 2013 and create a new project by selecting "Azure Cloud Service" under File > New. Add an "ASP.NET Web Role" to the project named WebRole1. Choose the "Web Forms" ...

Cypress eliminating the "X-CSRFToken" header

There seems to be an issue with the Cypress test runner where it is removing X-CSRFToken from the request header, leading to a 403 Forbidden error. I have compared the headers between a manual run and a Cypress test run, and you can see the difference in t ...

Utilize npm module by directly installing from GitHub repository

After finding that an npm package I wanted to use in my Meteor app was missing some features, I decided to take matters into my own hands. I forked the repo and applied the patch myself. To install the updated package, I used the following command: meteor ...

updating deeply nested structures in immutable JS

I encountered an 'invalid keypath' error while attempting to modify my structure: state = fromJS({ cmsData: { "pages": [ { "name": "page1", "content": { "header": "Example header", "intro": "Exampl ...

How to Decode JSON information using C#

There is a JSON data structure {{ "action": "rma", "devices": "[95001105,30013103,300117]", "devandreason": [ { "device": 95001105, "reason": 100 }, { "device": 30013103, "reason": 300 }, { "device": 300117, ...

jQuery show/hide function malfunctioning

Currently, I am attempting to create a basic show/hide interaction for a div using jQuery. The goal is to make the artists-home div vanish and be replaced by the .ken-gallery when the .artist-ken is clicked. Here is my current code, although it is not fun ...