locked
How Do I Load Different Partial Pages in Razor Pages Based on an ID Via AJAX RRS feed

  • Question

  • User-939035612 posted

    I have found several examples of how to dynamically load partial views in MVC based on some parameter, but none of them reproduce it using Razor Pages exactly how I need it done. I have a dropdown list that selects a category id in a form and then I need to load a different set of inputs depending on what category id is selected. I was thinking using partial pages would be the best way to do this. On my older projects that used web forms I could do this from code behind by getting the selected value of the drop down list, but I am not sure how to reference the dropdown list using .Net Core code behind.

    The closest I've seen to what I am looking for is https://www.learnrazorpages.com/razor-pages/ajax/partial-update but it does not pass a parameter. So far my code looks like this 

    public PartialViewResult OnGetCategoryPartial()
    		{
    			string partialname = "_CreateCommunity";
    			if (Posts.Category != null)
    			{
    				int? catid = Posts.Category;
    				switch (catid)
    				{
    					case 1:
    						partialname = "_CreateCommunity";
    						break;
    					case 2:
    						partialname = "_CreatePersonals";
    						break;
    					case 3:
    						partialname = "_CreateHousing";
    						break;
    					case 4:
    						partialname = "_CreateShopping";
    						break;
    					case 5:
    						partialname = "_CreateServices";
    						break;
    					case 6:
    						partialname = "_CreateJobs";
    						break;
    					case 8:
    						partialname = "_CreateRantrave";
    						break;
    				}
    
    			}
    			return Partial(partialname);
    		}

    Then the control on the page looks like this 

    <div class="form-group">
                <label asp-for="Posts.Category"></label>
                <select asp-for="Posts.Category" class="form-control" asp-items=@(new SelectList(@ViewBag.ListofCategories,"Categoryid", "Categoryname"))></select>
                <span class="text-danger" asp-validation-for="Posts.Category"></span>
            </div>

    The javascript for loading the partial looks like this

    $('#categorypartial').load('/post?handler=CategoryPartial');

    What is the best way to pass the Category ID? Should I use a querystring, routing, or is there a way to get the value from the drop down list in the partial view result?

    Wednesday, October 14, 2020 5:56 AM

Answers

  • User475983607 posted

    I would simplify the code and pass the partial name.  They way the content is data driven rather than hard coded.

    @page "{handler?}"
    @model RazorDemo.Pages.PartialDemo.IndexModel
    @{
        ViewData["Title"] = "index";
    }
    
    <h1>index</h1>
    
    <div>
        <select id="Category" name="Category">
            <option value="_CreateCommunity" selected>-- Select --</option>
            <option value="_CreateCommunity">Community</option>
            <option value="_CreatePersonals">Personals</option>
        </select>
    </div>
    <hr />
    <div id="content">
    
    </div>
    
    @section Scripts
    {
        <script>
            //Init
            $('#content').load('/PartialDemo/Index/CategoryPartial/?partialName=' + $('#Category').val());
    
            //Change event
            $('#Category').change(function () {           
                $('#content').load('/PartialDemo/Index/CategoryPartial/?partialName=' + $(this).val());
            });
        </script>
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorDemo.Pages.PartialDemo
    {
        public class IndexModel : PageModel
        {
            public void OnGet()
            {
            }
    
            public PartialViewResult OnGetCategoryPartial(string partialName)
            {
    			return Partial(partialName);
    		}
        }
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 14, 2020 1:22 PM
  • User-939035612 posted

    Thanks, I came up with something similar using routing, but I still had to hard code the partial names because the option values you were using are already bound to the categoryid field in the posts table. 

    .AddPageRoute("/post/Index", "/post/{Categoryid:int}")
    <select asp-for="Posts.Category" class="form-control" asp-items=@(new SelectList(@ViewBag.ListofCategories,"Categoryid", "Categoryname"))></select>
    $('#Posts_Category').change(function () {
                    var url = '@Url.Content("~/api/")' + "Categories/Getsubcategory/";
                    var ddlsource = "#Posts_Category";
                    $.getJSON(url + $(ddlsource).val(), function (data) {
                        var items = '';
                        $("#Posts_Subcategory").empty();
                        $.each(data, function (i, subcategory) {
                            items += "<option value='" + subcategory.value + "'>" + subcategory.text + "</option>";
                        });
                        $('#Posts_Subcategory').html(items);
                    });
                    $('#categorypartial').load('/post/' + $(ddlsource).val() + '?handler=CategoryPartial');
                });
    
    public PartialViewResult OnGetCategoryPartial(int Categoryid)
    		{
    			string partialname = String.Empty;
    			if (Categoryid != null)
    			{
    				switch (Categoryid)
    				{
    					case 1:
    						partialname = "_CreateCommunity";
    						break;
    					case 2:
    						partialname = "_CreatePersonals";
    						break;
    					case 3:
    						partialname = "_CreateHousing";
    						break;
    					case 4:
    						partialname = "_CreateShopping";
    						break;
    					case 5:
    						partialname = "_CreateServices";
    						break;
    					case 6:
    						partialname = "_CreateJobs";
    						break;
    					case 8:
    						partialname = "_CreateRantrave";
    						break;
    				}
    
    			}
    			return Partial(partialname);
    		}



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 14, 2020 10:49 PM

All replies

  • User503812343 posted

    you can use jQuery and Action method that return PartialViewResult from Controller.

    in js file add below code

     $(document).ready(function () {        
            
    // #partialviews is view name and /home/LoadPartialView is url to execute action method.
    $("#partialviews").load('/home/LoadPartialView/' + carid); });

    in controller

    public PartialViewResult LoadPartialView(int catid)
    {
    	switch (catid)
    	{
    		case 1:
    			partialname = "_CreateCommunity";
    			break;
    		case 2:
    			partialname = "_CreatePersonals";
    			break;
    		case 3:
    			partialname = "_CreateHousing";
    			break;
    		case 4:
    			partialname = "_CreateShopping";
    			break;
    		case 5:
    			partialname = "_CreateServices";
    			break;
    		case 6:
    			partialname = "_CreateJobs";
    			break;
    		case 8:
    			partialname = "_CreateRantrave";
    			break;
    	}
    
        return PartialView(partialname);
    }
    
    
    
    
    
    

    for more details visit - http://dotnetmentors.com/mvc/how-to-use-partial-view-in-mvc-with-example.aspx

    Wednesday, October 14, 2020 11:59 AM
  • User475983607 posted

    I would simplify the code and pass the partial name.  They way the content is data driven rather than hard coded.

    @page "{handler?}"
    @model RazorDemo.Pages.PartialDemo.IndexModel
    @{
        ViewData["Title"] = "index";
    }
    
    <h1>index</h1>
    
    <div>
        <select id="Category" name="Category">
            <option value="_CreateCommunity" selected>-- Select --</option>
            <option value="_CreateCommunity">Community</option>
            <option value="_CreatePersonals">Personals</option>
        </select>
    </div>
    <hr />
    <div id="content">
    
    </div>
    
    @section Scripts
    {
        <script>
            //Init
            $('#content').load('/PartialDemo/Index/CategoryPartial/?partialName=' + $('#Category').val());
    
            //Change event
            $('#Category').change(function () {           
                $('#content').load('/PartialDemo/Index/CategoryPartial/?partialName=' + $(this).val());
            });
        </script>
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace RazorDemo.Pages.PartialDemo
    {
        public class IndexModel : PageModel
        {
            public void OnGet()
            {
            }
    
            public PartialViewResult OnGetCategoryPartial(string partialName)
            {
    			return Partial(partialName);
    		}
        }
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 14, 2020 1:22 PM
  • User-939035612 posted

    Thanks, I came up with something similar using routing, but I still had to hard code the partial names because the option values you were using are already bound to the categoryid field in the posts table. 

    .AddPageRoute("/post/Index", "/post/{Categoryid:int}")
    <select asp-for="Posts.Category" class="form-control" asp-items=@(new SelectList(@ViewBag.ListofCategories,"Categoryid", "Categoryname"))></select>
    $('#Posts_Category').change(function () {
                    var url = '@Url.Content("~/api/")' + "Categories/Getsubcategory/";
                    var ddlsource = "#Posts_Category";
                    $.getJSON(url + $(ddlsource).val(), function (data) {
                        var items = '';
                        $("#Posts_Subcategory").empty();
                        $.each(data, function (i, subcategory) {
                            items += "<option value='" + subcategory.value + "'>" + subcategory.text + "</option>";
                        });
                        $('#Posts_Subcategory').html(items);
                    });
                    $('#categorypartial').load('/post/' + $(ddlsource).val() + '?handler=CategoryPartial');
                });
    
    public PartialViewResult OnGetCategoryPartial(int Categoryid)
    		{
    			string partialname = String.Empty;
    			if (Categoryid != null)
    			{
    				switch (Categoryid)
    				{
    					case 1:
    						partialname = "_CreateCommunity";
    						break;
    					case 2:
    						partialname = "_CreatePersonals";
    						break;
    					case 3:
    						partialname = "_CreateHousing";
    						break;
    					case 4:
    						partialname = "_CreateShopping";
    						break;
    					case 5:
    						partialname = "_CreateServices";
    						break;
    					case 6:
    						partialname = "_CreateJobs";
    						break;
    					case 8:
    						partialname = "_CreateRantrave";
    						break;
    				}
    
    			}
    			return Partial(partialname);
    		}



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 14, 2020 10:49 PM