Home >Backend Development >C++ >How to Render a Partial View in ASP.NET MVC on Button Click without Page Reload?
Rendering a Partial View on Button Click in ASP.NET MVC
In ASP.NET MVC, rendering a partial view in response to a button click is a common task. This allows you to dynamically update a specific section of the page without reloading the entire page.
Problem Description:
The provided code attempts to display a partial view in a specific div on the page after a button click. However, the button navigates to a different URL, causing the entire page to reload. The goal is to render the partial view within the div on the client side.
Solution:
To achieve this, it is necessary to handle the button click using JavaScript and perform an AJAX request to the server. The following steps describe how to accomplish this:
<button>
var url = '@Url.Action("DisplaySearchResults", "Search")'; $('#search').click(function() { var searchText = $('#Keyword').val(); $('#searchResults').load(url, { searchText: searchText }); });
public ActionResult DisplaySearchResults(string searchText) { // Build a list of search results based on the searchText var model = ... return PartialView("SearchResults", model); }
The JavaScript code handles the button click, retrieves the search text from the page, and uses jQuery's .load method to make an AJAX request to the DisplaySearchResults action. The server generates the partial view and sends it to the client, which then updates the content of the #searchResults div.
Note:
If the model for the Index view contains properties with validation attributes, it is recommended to add a submit button instead of a button. The JavaScript code should handle the form's .submit event and perform validation before making the AJAX request.
The above is the detailed content of How to Render a Partial View in ASP.NET MVC on Button Click without Page Reload?. For more information, please follow other related articles on the PHP Chinese website!