Solved

ASP.NET MVC 5 Partial View issue

Posted on 2014-02-19
7
1,554 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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 

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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

776 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