KeelRisk
KeelRisk

Reputation: 749

How do you only show your results after the user clicks search in an Asp.Net MVC application

I have an Index.cshtml view, a Filter.cshtml partial view and Results.cshtml partial view. I want to see values from my Results.cshtml parital view after the user has clicked the search button, along with the content from Index.cshtml and Filter.cshtml. How do I structure my page(s) to see content from Results.cshtml after the search button is clicked, along with other content?

This is what I have for my Index.cshtml view

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

@{ Html.RenderPartial("Filter"); }
@{ Html.RenderPartial("Results"); }

Upvotes: 0

Views: 749

Answers (2)

Tx3
Tx3

Reputation: 6916

If you can use jQuery then you could do something like this

In your View you could have a container for results

Html

<div id="result-container"></div>

And using jQuery you would get the content when submit is clicked

JavaScript

$(document).ready(function () {
    $('#submit').click(function () { 
        $.ajax({
            type: 'GET',
            url: 'YourController/ActionThatReturnPartialView',
            data: {
                // your form data here
            }
        }).done(function (html) {
            // place the partial view to the container
            $('#result-container').html(html);
        });            
    });
});

Controller

public class YourController
{    
    public ActionResult ActionThatReturnPartialView()
    {
         // get parameters and do some logic
         return PartialView(model);     
    }    
}

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039100

You could use a view model:

public class MyViewModel
{
    public string Filter { get; set; }
    public string Results { get; set; }
}

and then:

public class HomeController: Controller
{
     public ActionResult Index()
     {
         return View(new MyViewModel());
     }

     [HttpPost]
     public ActionResult Index(MyViewModel model)
     {
         model.Results = "this is the result"; 
         return View(model);
     }
}

and in the view:

@model MyViewModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@{ Html.RenderPartial("Filter"); }
@if (Model.Results != null)
{
    @{ Html.RenderPartial("Results"); 
}

and using templates:

@model MyViewModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@Html.EditorFor(x => x.Filter)
@if (Model.Results != null)
{
    @Html.DisplayFor(x => x.Results)
}

Upvotes: 0

Related Questions