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:
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!