简体   繁体   中英

Dynamically rendering a partial view in ASP .NET MVC 4

I'm busy investigating possibilities for the following:

I have a 'Search' view. I have a 3 entities, Person, Car and House. I want to use this Search screen to dynamically build the search criteria based on the entity type selected by the user.

If the user wants to search for 'Person', then I want to dynamically return a partial view for Person specific search criteria, like Name. Or if they selected Car, it returns a different partial view for search criteria of 'Engine Size', etc.

How do achieve this? If I could return the partial view via an ajax call to the controller method (to avoid the postback), that'll be a huge bonus.

First render all your partials in their very own div like so

<div id="personSearch">
    @Html.Partial("PartialView1")
</div>

<div id="carSearch">
    @Html.Partial("PartialView1")
</div>

<div id="houseSearch">
    @Html.Partial("PartialView1")
</div>

jQuery code, we first off hide all 3 of those filters, then we can dynamically should the div's depending on the criteria selected by the user

So something like so

$(function()
{
    // Hide all divs
    $('#personSearch').hide();
    $('#carSearch').hide();
    $('#houseSearch').hide();

    // This is the ID of a dropdownlist for Person, Car or House selection
    $('#UserCriteria').change(function ()
    {
        var value = $(this).val();

        // 1 id the int id for Person
        if(value == 1)
        {
            $('#personSearch').slideDown();
            $('#carSearch').slideUp();
            $('#houseSearch').slideUp();
        }
        // 2 id the int id for Car
        if(value == 2)
        {
            $('#personSearch').slideUp();
            $('#carSearch').slideDown();
            $('#houseSearch').slideUp();
        }
        // 3 id the int id for House
        if(value == 3)
        {
            $('#personSearch').slideUp();
            $('#carSearch').slideUp();
            $('#houseSearch').slideDown();
        }
    }.change();
});

So what we are really doing here, is basically rendering all partial views on to the page, however using the .change() on our $('#UserCriteria') if the default value is null nothing will happen, however if the default value is "Person" (id = 1). the personSearch div will slideDown and will display your Partial view.

I hope this is what you were looking for :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM