Display Partial View in MVC 4 using ajax success callback

Issue: Unable to load view on ajax success.

Situation: I have two cascaded dropdowns where the second dropdown's options are based on the selection of the first dropdown. Upon selecting an option in the second dropdown, I want to display a list of records corresponding to the selected values from both dropdowns.

To achieve this functionality, I am using the following JavaScript code for handling the onchange event of the second dropdown:

function ShowDocsList() {
        var teamId = $('#TeamID').val();
        var projectId = $("#ProjectID").val();
        var Url = "@Url.Content("~/DocsHome/DocsList")";
        $.ajax({
            url: Url,
            type:'POST',
            dataType: 'html',
            data: { TeamID: teamId ,ProjectID : projectId},
            success: function (data) {
              $('.docs-detail').html(data);
            }
        });
}

The issue arises when trying to render the view in the DocsHome Controller's DocsList method upon changing the second dropdown selection. The controller code is as follows:

 public ActionResult DocsList(int teamId, int projectId)
        {
            List<CustomerViewModel> customerViewsModels = SmartAdminHelper.GetCustomers(db1);
            if (Request.IsAjaxRequest())
                return PartialView("DocsList");
            else
                return View("DocsList");

        }

Although the record is retrieved in the list, it does not pass to the DocsList view while debugging, which seems correct to me at first glance.

I expect the DocsList view to be rendered as a partial view upon changing the second dropdown. During debugging, the process comes to the point of returning PartialView("DocsList"), but then it goes back to the ajax success method, indicating a mistake in my implementation.

Prior to this, I used JSON to fetch data, but now I'm calling an action method through ajax, which might also be causing the issue since I am relatively new to this concept.

Where exactly am I making an error and how can I resolve it?

Answer №1

Saroj, I understand that this question is from a while ago and you needed a quick solution. However, if you happen to revisit this, here's my input. You should remove the return statement mentioned by David and Ehsan above. The rest of the callback function seems to be working fine. It appears that in your action method, you are not utilizing the parameters you pass in. I assume you will handle that once you have the view ready for the client. Let's focus on getting the view to the client.

My approach involves returning the rendered partial view as an HTML string to the client. I achieve this by using a method stored in a base controller class inherited by all my controllers. To successfully implement this method, you need to include references to System.Web.Mvc and System.IO namespaces.

The method is structured as follows:

private string RenderViewToString( string viewName, object model ) {
            ViewData.Model = model;
            using ( var sw = new StringWriter() ) {
                var viewResult = ViewEngines.Engines.FindPartialView( ControllerContext, viewName );
                var viewContext = new ViewContext( ControllerContext, viewResult.View, ViewData, TempData, sw );
                viewResult.View.Render( viewContext, sw );
                viewResult.ViewEngine.ReleaseView( ControllerContext, viewResult.View );
                return sw.GetStringBuilder().ToString();
            }
        }

You provide the model and view name to the method, and it returns the rendered view as an HTML string. This string can then be sent back to the client as a ContentResult.

Update your action method with the following code:

 public ActionResult DocsList(int teamId, int projectId)
            {
                List<CustomerViewModel> customerViewsModels = SmartAdminHelper.GetCustomers(db1);
                if (Request.IsAjaxRequest())
                    var viewContents = RenderViewToString("DocsList", customerViewsModels);
                    return Content(viewContents);
                else
                    return View("DocsList");

            }

If the target element where the rendered view should display has the CSS class '.docs-detail', you should be good to go. Hopefully, this information proves helpful!

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

Issue with the functionality of Material-ui tooltip

I'm exploring the implementation of the material-ui tooltip feature and I am hoping to have it displayed at the top of the element. Despite specifying placement="top", the tooltip still does not appear as intended. You can view a demo of this issue b ...

Transforming the timezone of a date from the Backend to the timezone selected by the user in the User

I have an API that provides dates in the format: 12/23/2023 at 03:31 a.m. CST My goal is to convert this to a date with the user-selected timezone in the following format: 12/23/2023 at 7:31 p.m. The timezone part is not required for display in the UI. c ...

Extract Data from JSON Array using Jquery

I am working with a JSON array retrieved from a web API, and I need to extract specific values from it. For instance, how can I retrieve all the rides in the first place and access rides[1]. UserID or Images? { "Status":1, "Rides& ...

Retrieve the following span that has the specified class

I am working with the following HTML structure for <select> elements on my webpage: <div class="clsPropertyDiv clsPropertyId_16 "> <span class="inputTitle">You can select multiple items</span><br> <select i ...

Tips for resolving an issue with mongoose Model.create becoming unresponsive indefinitely

I'm having trouble understanding why my mongoose Model.create operation isn't completing successfully. The same connection is working well with other controller functions. vscode postman I am attempting to create a new document, but my code s ...

Input field in a tableview

I have a ListView that features a dropdown, 4 textboxes and buttons. My goal is to only show the fourth textbox (enclosed in a span) when the dropdown value in each row of the ListView is set to 2. For instance, if there are 5 records being displayed in t ...

Passing Variables from Node JS to Pug Template's HTML and JavaScript Sections

Here is a route that sends various variables to a Pug template: items.js route router.get('/edit/:itemObjectId', async function(req, res, next) { var itemObjectId = req.params.itemObjectId; var equipmentCategoryArr = []; var lifeExp ...

Clicking on a href link inside a scrollable div-container causes it to malfunction, causing the page to jump

I have a draggable div container that contains dynamically generated content. In order to display this container, I use the following code: $( function() { $( "#dialog-message" ).dialog({ modal: true, height: 400, buttons: { Fertig: functi ...

In JavaScript, the code is designed to recognize and return one specific file type for a group of files that have similar formats (such as 'mp4' or 'm4v' being recognized as 'MOV')

I am working on a populateTable function where I want to merge different file types read from a JSON file into one display type. Specifically, I am trying to combine mp4 and m4v files into MOV format. However, despite not encountering any errors in my code ...

Changing pricing on pricing table with a click

Looking to implement a price changing button that functions similar to the one found at this LINK: If anyone knows of any JavaScript or other solution, please provide me with some guidance. Thank you in advance. ...

Deliver a communication from the dialogue box on the MEAN stack website to the task pane

Currently experimenting with the Dialog API within Office addins. Able to successfully trigger a Dialog box from my task pane using: $scope.openDialog = function () { Office.context.ui.displayDialogAsync('https://localhost:3000/home', ...

How can we ensure the discord client object is easily accessible within event files?

I'm a beginner with Discord.js and I've been trying to figure out how to allow event and command files to access the main client instance. I want to be able to call client.database in an event file for CRUD operations, but I'm confused on ho ...

I have implemented a button in PHP and now I am looking to invoke a function when that button is clicked

I have a PHP-generated HTML button and I'm having trouble calling the mybtn3() function when it is clicked. The button code looks like this: echo"<td width=14% align=center><input type=button value=Export onclick=mybtn3() /></td>"; ...

How to arrange a collection of objects in JavaScript

I am facing a challenge with sorting the array based on the address._id field of each object. Despite attempting to use the lodash orderby function, I have not been able to achieve the desired outcome. [{ rider_ids: '5b7116ea3dead9870b828a1a& ...

Difficulty altering value in dropdown using onChange function - Material-UI Select in React app

Having trouble updating dropdown values with MUI's Select component. The value doesn't change when I use the onChange handler, it always stays the same even after selecting a new item from the dropdown. I made a functional example on CodeSanbox. ...

Tips for aligning pagination in the MUI v5 table component and creating a fixed column

I am currently experimenting with MUI table components and have created an example below with pagination. const MuiTable = () => { const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [data, setData] ...

Trouble getting CSS to load in Webpack

I'm having some trouble setting up Webpack for the first time and I think I might be overlooking something. My goal is to use Webpack's ExtractTextPlugin to generate a CSS file in the "dist" folder, but it seems that Webpack isn't recognizi ...

Discovering an npm module within an ember-cli addon component

I recently encountered an issue while using ember-browserify to locate npm modules in my ember-cli applications - it seems to not function properly for ember-cli addons. This leads me to wonder: Are there alternative methods for importing npm modules into ...

Searching for specific data within an embedded documents array in MongoDB using ID

While working with mongodb and nodejs to search for data within an embedded document, I encountered a strange issue. The query functions as expected in the database but not when implemented in the actual nodejs code. Below is the structure of my data obje ...

Leverage the power of openCv.js within your next.js projects

I am attempting to incorporate openCv.js into my next.js application a. I started the project with: npx create-next-app b. Next, I installed: $ yarn add @techstark/opencv-js c. Imported OpenCV with: import cv from "@techstark/opencv-js" d. Ho ...