Home >Backend Development >C++ >How to Dynamically Render a Partial View in ASP.NET MVC on Button Click?

How to Dynamically Render a Partial View in ASP.NET MVC on Button Click?

DDD
DDDOriginal
2025-01-04 22:01:41328browse

How to Dynamically Render a Partial View in ASP.NET MVC on Button Click?

Rendering Partial View Dynamically upon Button Click in ASP.NET MVC

Problem Description:

In ASP.NET MVC, you want to render a partial view inside a specific div on the client side when a button is clicked, and the partial view should use data obtained dynamically during the button event.

Code Example:

Consider the following button code:

<button type="button">

This button attempts to navigate to a separate URL when clicked. To instead handle the click event and dynamically render the partial view, we need to modify the code as follows:

<button>

Additionally, add the following script to the page:

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val(); // Retrieve the user-entered search text
  $('#searchResults').load(url, { searchText: keyWord });
});

Modify the controller method to accept the search text as an argument:

public ActionResult DisplaySearchResults(string searchText)
{
  // Build list based on the provided searchText and return the partial view
  var model = // To be implemented
  return PartialView("SearchResults", model);
}

Explanation:

  • The jQuery .load method makes an AJAX call to the specified URL, passing any data provided in the data parameter.
  • The controller method is responsible for generating the partial view based on the dynamically provided data.
  • The updated content is loaded into the #searchResults div, dynamically rendering the partial view.

Note: If your model class contains multiple properties with validation attributes, replace the onclick handling with the following code and use a submit button instead:

$('form').submit(function() {
  if (!$(this).valid()) { return false; }
  var url = '@Url.Action("DisplaySearchResults", "Search")';
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false;

In this case, the controller method should handle the complete SearchCriterionModel object:

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
  var model = // Build list based on the properties of criteria and return the partial view
  return PartialView("SearchResults", model);
}

The above is the detailed content of How to Dynamically Render a Partial View in ASP.NET MVC on Button Click?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn