Search code examples
asp.net-mvcactionlink

ASP.NET MVC 5: How do you render a partial view in a div from an action link?


I am new to ASP.NET and web development of any kind. I have searched for many hours for a solution to my problem, but I can't seem to get my partial view to show up in the div.

What is happening is the view is showing up, but it's replacing the entire page instead of showing up in the div within the main page.

My controller looks something like this:

public class MyController
{
    public ActionResult ShowView(int id)
    {
        // get view model from id
        return PartialView(viewModel);
    }
}

My Main View looks something like this

@model List<viewModelType>

<div>
    @foreach (var item in Model)
    {
        <div>
            @Html.ActionLink(item.Name, "ShowView", new { id = item.ID }, new { @class = "btn-sm" })
        </div>
    }
</div>

<div>
    // here is where I want to partial view to go!
</div>

This is what the partial view looks like:

@model viewModelType
<div>Model.DataToDisplay</div>

Solution

  • Okay I figured it out with Christos' help.

    The main view should look like this:

    @model List<viewModelType>
    
    <div>
        @foreach (var item in Model)
        {
            <div>
                <button class="js-showViewBtn" [email protected]>item.Name</button>
            </div>
        }
    </div>
    
    <div class="js-show-view">
        // here is where I want to partial view to go!
    </div>
    
    <script type="text/javascript">
        $(function () {
            $('.js-showViewBtn').click(function (e) {
                e.preventDefault();
                var itemId = $(this).data("itemId");
    
                $.ajax({
                    method: "GET",
                    url: "/MyController/ShowView",
                    data: { id: itemId },
                    cache: false
                }).success(function(data){
                    $('.js-show-view').html(data);
                });
            })
        });
    </script>
    

    For some reason the id of the item was not being returned, so I tried it like this and it worked. Hope this helps others too.

    Thanks for your help Christos.