1

I have a form with some input fields. When a user clicks on the submit I want to post the fields back, use them to query a service and load some results into a view on the same page while preserving the original input. For this, I've scaffolded a view using my model and added a partial view below to populate the results with.

....bottom of form <div class="form-group">
        @Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Amount, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PostalAmount, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Search" class="btn btn-default" />
        </div>
    </div>
</div>

<div class="list-group">
    @Html.Partial("_ResultsPartial")
</div>

In my controller, I have 2 actions, one to create the initial view and one for the post back.

        [HttpGet]
    public ActionResult Search()
    {
        ViewBag.Message = "Enter search details";

        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public PartialViewResult Search(SearchCriteria searchCriteria)
    {
        List<SearchResult> results = new List<SearchResult>();
        if (ModelState.IsValid)
        {
           //await go off and do the actaul search
           results = _dataProvider.GetData(searchCriteria);
        }
        return PartialView("~/Views/Shared/_ResultsPartial.cshtml", results);
    }

So in order to render the partial view, I use return PartialView passing in the new model which contains the results of my search. One of the problems I'm having with this is that creates a new page, i.e. the partial view doesn't load on the existing page. What other way is there to render a partial view while in a controller action so that the partial view loads on the page it was created?

Pawan Patil
  • 1,067
  • 5
  • 20
  • 46
user48408
  • 3,234
  • 11
  • 39
  • 59
  • Use ajax to call a method that returns your partial view, and update the existing page. –  Aug 04 '17 at 11:24
  • Sounds ok. But i'm really looking for the path of least resistance. This is not production code. With my given setup at the moment is there an even easier way – user48408 Aug 04 '17 at 11:27
  • Refer [this question/answer](https://stackoverflow.com/questions/29142422/rendering-partial-view-on-button-click-in-asp-net-mvc/29142790#29142790) –  Aug 04 '17 at 11:28

2 Answers2

0

Try replacing your rendering with something like:

@{Html.RenderAction("Results", new {results = model.Results})};
Tom John
  • 783
  • 5
  • 14
0

Try this one

return PartialView("_ResultsPartial", results);
Ajmal Jamil
  • 799
  • 1
  • 8
  • 15