Robert Ross
Robert Ross

Reputation: 1189

Not sure how to properly use a partial view

I read a lot of questions here on stacoverflow, but it is still not clear to me how should I use a partialview within a main view with an action method. What's probably wrong is my aproach in general. With what I have so far I am not sure how to continue with my code.

I will start with the main view :

 @{
        ViewBag.Title = "getRolesByYear";
    }
    </script>
    <script type="text/javascript">


        getRolesForYear(parseInt(@DateTime.Now.Year));

        $(function () {
            $('#years a').click(function () {
                var year = $(this).text();
                console.log(year);
                getRolesForYear(parseInt(year));
            });
        })
        //console.log(year);


        function getRolesForYear(year) {
            console.log(year);
            $.ajax({
                type: "POST",
                url: '@Url.Action("getRolesByYear", "WorkRoles")',
                dataType: "json",
                data: {
                    year: year
                },
                success: successFunc,
                error: errorFunc
            });

            function successFunc(data, status) {
                console.log('x');
                }

            }

            function errorFunc() {
                alert('error');
            }
        }



    </script>

    <div id = "years" class="btn-group btn-group-justified timeline">
        <a  href="#@DateTime.Now.Year" class="btn btn-primary">@DateTime.Now.Year</a>
        <a  href="#@DateTime.Now.AddYears(-1).Year" class="btn btn-primary">@DateTime.Now.AddYears(-1).Year</a>
        <a  href="#@DateTime.Now.AddYears(-2).Year" class="btn btn-primary">@DateTime.Now.AddYears(-2).Year</a>
    </div>

<div id"partial"></div>

In this view I have three buttons with different year for each button. On page load or on button click I make an ajax call to an action method with the an int year as a parameter.

This is a simplified version of my action method :

public ActionResult getRolesByYear(int year)
    {


      // a couple of queries here


        var list = list of RoleViewModel objects;

        return PartialView(list);

And here is the partialView :

@model IEnumerable<eksp.Models.RoleViewModel>


@foreach (var item in Model)
{
    <div class="jumbotron">
        <h2>item.Role.RoleName</h2>

        <h1> item.Role.RoleDescription</h1>
        <p class="lead">Focus start : item.Role.FocusStart</p>
        <p>Focus end : item.Role.FocusStart </p>

    </div>
}

Obviously, a lot of thins aren't clear to me. How can I use this partial view with the action method i have and the main view? Do I need a separate method for the partial view? Any tips?

Upvotes: 0

Views: 70

Answers (2)

Shyju
Shyju

Reputation: 218892

Your ajax call will invoke the action method which returns the partial view result (markup generated by executing the partial view). I guess you simply need to use the response of the ajax call to update your DOM.

If you want to update the content of the div with id partial with the response, you can do that in the success event handler of your ajax call.

success : function(response)
{
  $("#partial").html(response);
}

I would also recommend to call the getRolesForYear method on document ready event.

$(function () {

       getRolesForYear(parseInt(@DateTime.Now.Year));

        $('#years a').click(function () {
            var year = $(this).text();
            console.log(year);
            getRolesForYear(parseInt(year));
        });
})

Also, If your main view is also the result of action method getRolesByYear, you probably want to return the partial view result only on the ajax call, the other calls,you can return the partial view

public ActionResult getRolesByYear(int year)
{
    var list = list of RoleViewModel objects;
    if(Request.IsAjaxRequest())
    {
       return PartialView(list);
    }
    else
    {
      return View(list);
    }
}

Here the same action method handles the request for main view and ajax call. It returns the same view for ajax call, but using PartialView call, so layout will be ignored. But If you have a specific view you want to return, you can do that as well.

if(Request.IsAjaxRequest())
{
    return PartialView("_yearlyRoles",list);
}

Upvotes: 1

DKar
DKar

Reputation: 514

One of the reasons I like using partial views for rendering data via Ajax calls. For example if I want to start searching in order to avoid the server call i Just use an ajax call to the controller which returns the search results through a partial view. In your example yoy need to load the results in partial div.

function successFunc(data, status) {
     $("#partial").html(data);
}

Upvotes: 0

Related Questions