Rendering partial view on button click in ASP.NET MVC
So here is the controller code.
public IActionResult AddURLTest()
{
return ViewComponent("AddURL");
}
You can load it using JQuery load method.
$(document).ready (function(){
$("#LoadSignIn").click(function(){
$('#UserControl').load("/Home/AddURLTest");
});
});
source code link
Change the button to
<button id="search">Search</button>
and add the following script
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
var keyWord = $('#Keyword').val();
$('#searchResults').load(url, { searchText: keyWord });
})
and modify the controller method to accept the search text
public ActionResult DisplaySearchResults(string searchText)
{
var model = // build list based on parameter searchText
return PartialView("SearchResults", model);
}
The jQuery .load
method calls your controller method, passing the value of the search text and updates the contents of the <div>
with the partial view.
Side note: The use of a <form>
tag and @Html.ValidationSummary()
and @Html.ValidationMessageFor()
are probably not necessary here. Your never returning the Index
view so ValidationSummary
makes no sense and I assume you want a null
search text to return all results, and in any case you do not have any validation attributes for property Keyword
so there is nothing to validate.
Edit
Based on OP's comments that SearchCriterionModel
will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit()
event
<input type="submit" value="Search" />
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
if (!$(this).valid()) {
return false; // prevent the ajax call if validation errors
}
var form = $(this).serialize();
$('#searchResults').load(url, form);
return false; // prevent the default submit action
})
and the controller method would be
public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
var model = // build list based on the properties of criteria
return PartialView("SearchResults", model);
}