Solved

ASP.NET MVC 5 Partial View issue

Posted on 2014-02-19
7
1,532 Views
Last Modified: 2014-02-26
Hi,
I'm working on coding a new website for my church.  However I'm having a problem where the Partial View not being rendered in the original view.  Instead it is populating a new page.  I have installed the jquery.unobtrusive-ajax.min.js.

StaffController.cs
public class StaffController : LightSpeedControllerBase<ModelUnitOfWork>
    {
        protected override LightSpeedContext<ModelUnitOfWork> LightSpeedContext
        {
            get { return MvcApplication.LightSpeedContext; }
        }
        //
        // GET: /Staff/
        [HttpGet]
        public ActionResult Index()
        {
            var churchStaff = UnitOfWork.Staffmembers.WithViewName("staffmembers").Where(staffmember => staffmember.Active && staffmember.Showasstaff)
                .OrderBy(staffmember => staffmember.Positionid)
                .ThenBy(staffmember => staffmember.Displayorder).ToList();

            var positions = from s in UnitOfWork.Staffpositions
                select s;

            var churchPositions = new SelectList(positions, "Id", "Name").ToList();
            churchPositions.Insert(0, new SelectListItem() { Selected = true, Text = "All", Value = "-1"});

            ViewData["StaffPositions"] = churchPositions;
            return View("Index", churchStaff);
        }

        [HttpPost]
        public PartialViewResult GetStaffByPosition(int pos)
        {
            var churchStaff =
               UnitOfWork.Staffmembers.WithViewName("staffmembers")
                   .Where(staffmember => staffmember.Active && staffmember.Showasstaff && staffmember.Positionid == pos)
                   .OrderBy(staffmember => staffmember.Displayorder).ToList();

            return PartialView("_churchstaff", churchStaff);
        }
	}

Open in new window


Index.cshtml
@using PCC.Site.Models;
@{
    ViewBag.Title = "Staff | Paragon Christian Church";
    var x = 0;
}
<script type="text/javascript" src="~/Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript" src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

@section Slider
{    	<!-- - - - - - - - - - - - - - Page Header - - - - - - - - - - - - - - - -->		
	<section class="page-header">
		<div class="container">
			<h1>Staff</h1>
		</div><!--/ .container-->
	</section><!--/ .page-header-->
}

<section class="main container sbr clearfix">	
		
	<!-- - - - - - - - - - Breadcrumbs - - - - - - - - - - - - -->		
	<div class="breadcrumbs">
		<a title="Home" href="@Url.Action("Index", "Home")">Home</a>
		<span>Staff</span>
	</div><!--/ .breadcrumbs-->
    <!-- - - - - - - - - end Breadcrumbs - - - - - - - - - - - -->

    <div style="float: right; border: 1px">
        @using (Ajax.BeginForm("GetStaffByPosition", new AjaxOptions()
        {
            HttpMethod = "Post",
            UpdateTargetId = "staffdiv",
            InsertionMode = InsertionMode.Replace
        }))
        {
            <text><label for="test" style="float: left; display: block">Position: </label></text>
            @Html.DropDownList("pos", (IEnumerable<SelectListItem>)ViewData["StaffPositions"],new {onchange="this.form.submit();"})
        }
    </div><!--/ .widget-->
    <div id="staffdiv">
        @{Html.RenderPartial("_churchstaff");}
    </div>
</section>

Open in new window


_churchstaff.cshtml
@model List<PCC.Site.Models.Staffmember>
@{
    var x = 0;
}

@foreach (var person in Model)
{
    if (x > 0)
    {
        <div class="border-divider"></div>
    }

    <div class="four columns">
        <div class="bordered">
            <figure class="add-border">
                <a class="single-image" href="#">
                    <img src="
                        @if (string.IsNullOrEmpty(person.Staffimage))
                        {
                            @:images/temp/staff-img-1.jpg
                        }
                        else
                        {
                            @person.Staffimage
                        }
                        " alt="" />
                </a>
            </figure>
        </div><!--/ .bordered-->
			
    </div>
    <!--/ .four .columns-->

    <div class="twelve columns">
			
        <h4 class="with-desc" data-desc="(@(person.Position))">
            @if (person.Recruting)
            {
                <i>We are currently recruiting for this position.</i>
            }
            else
            {
                <text>@person.Firstname @person.Lastname</text>
            }
        </h4>
			
        @if (!person.Recruting)
        {
            <p>
                @(person.Description)
            </p>
        }
        <a href="#" class="button default small">
            @if (person.Recruting)
            {
                @:Email for details
            }
            else
            {
                @:Contact me
            }
        </a>
			
    </div>
    <!--/ .twelve .columns-->

    x++;
}

Open in new window

0
Comment
Question by:yewnix
  • 4
  • 3
7 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 39873299
If you are talking about this HTML

    <div id="staffdiv">
        @{Html.RenderPartial("_churchstaff");}
    </div>

Open in new window


how is it rendered in the final output?
0
 

Author Comment

by:yewnix
ID: 39873408
In the beginning output from Index.cshtml it appears 100% correct.  However when I use the dropdown list and select a new position it then shows a new page with the filtered results(with no layout etc).
http://new.paragonchristian.com/Staff
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 39873848
It looks like you have a GetStaffByPosition action method, but I can't see that one in a controller.

What view is shown in that action method?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:yewnix
ID: 39873863
It is in the StaffController.cs

[HttpPost]
        public PartialViewResult GetStaffByPosition(int pos)
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 39874846
Too much code, too little time...

 [HttpPost]
        public PartialViewResult GetStaffByPosition(int pos)
        {
            var churchStaff =
               UnitOfWork.Staffmembers.WithViewName("staffmembers")
                   .Where(staffmember => staffmember.Active && staffmember.Showasstaff && staffmember.Positionid == pos)
                   .OrderBy(staffmember => staffmember.Displayorder).ToList();

            return PartialView("_churchstaff", churchStaff);
        }
	}

Open in new window


You shouldn't return a partial view as the ViewResult, you should return a full view that references the partial view.  The Index.cshtml view handles rendering the partial view.

   <div id="staffdiv">
        @{Html.RenderPartial("_churchstaff");}
    </div>

Open in new window

0
 

Accepted Solution

by:
yewnix earned 0 total points
ID: 39876779
I was able to solve my problem.  Your method did not solve my issue.  I still returned the PartialView as I was doing.
However I changed my main view.
@{
    Layout = "../Shared/_Layout.cshtml";
    ViewBag.Title = "Index";
}

<script>
    function OnChangeHandler() {
        $("form[name='positionForm']").trigger('submit');
    }
</script>

<h2>Index</h2>

@using(Ajax.BeginForm("AjaxTest", "Home", new AjaxOptions() { UpdateTargetId = "testdiv"}, new {@name = "positionForm"}))
{
    @Html.DropDownList("cat", (IEnumerable<SelectListItem>)ViewBag.MovieType, new { onchange = "OnChangeHandler();"})
}
<div id="testdiv">
   @Html.Partial("Partial1")
</div>

Open in new window

0
 

Author Closing Comment

by:yewnix
ID: 39888288
I found my own solution.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
I designed this idea while studying technology in the classroom.  This is a semester long project.  Students are asked to take photographs on a specific topic which they find meaningful, it can be a place or situation such as travel or homelessness.…

930 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now