I have a search form, which will do some client side validation, call the server action, do some server side validation, and then return either the original view (with the modelstate errors) OR the search results.
For this approach to work, i would need to render the view to a string, and return a Json result. I could probably do that with one of the answers in this question: Render a view as a string
However, if i'm having to implement my own 'RenderView' type function, is this really the best way to do this? Or is there a better design decision for implementing this kind of functionality? Any help would be greatly appreciated.
An abstraction of the code is listed below for reference;
Controller:
public ActionResult Index()
{
return View(new SearchModel());
}
public ActionResult Search(SearchModel criteria)
{
if (!ModelState.IsValid)
return Json(new { HasErrors = true, Result = RenderViewToString("Index", criteria) });
var results = {Do Search...};
return PartialView("SearchResults", results);
}
View:
@using(Html.BeginForm(...))
{
{form fields...}
{submit button...}
}
<div id="search-results"></div>
<script type="text/javascript">
$(document).on("submit", "form", function(e) {
if (!$(this).valid()) return false;
e.preventDefault(); // Submit the form with ajax instead.
$.ajax({
url: this.action,
type: this.method
data: $(this).serialize(),
success: function(data) {
if (data.HasErrors) {
$(document).html(data.Result);
}
else {
$("#search-results").html(data);
}
}
});
});
</script>