Need help on partial view using jQuery / Ajax

Jerry Lipan 916 Reputation points
2022-02-25T05:10:53.727+00:00

Hi,

I need help, User select City from Drop Down with ChangeData event. Then, in same page it will populate Food Data based on Value. Please bear in mind, this page will started with default value in Drop Down

177742-ezgifcom-gif-maker.gif

I dont know - How jQuery / Ajax look like. So far, I've this

Models ( FoodGet.cs )

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
  
namespace PartialViewWithoutReloadWholePage.Models  
{  
    public class FoodGet  
    {  
        public string Id { get; set; }  
        public string Value { get; set; }  
        public string FoodName { get; set; }  
    }  
}  

Controllers ( CityController.cs )

using Microsoft.AspNetCore.Mvc;  
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Mvc.Rendering;  
using PartialViewWithoutReloadWholePage.Models;  
  
namespace PartialViewWithoutReloadWholePage.Controllers  
{  
    public class CityController : Controller  
    {  
        public IActionResult Index()  
        {  
            //Creating the List of SelectListItem, this list you can bind from the database.  
            List<SelectListItem> cities = new()  
            {  
                new SelectListItem { Value = "1", Text = "New York" },  
                new SelectListItem { Value = "2", Text = "Milan" },  
                new SelectListItem { Value = "3", Text = "Tokyo" },  
                new SelectListItem { Value = "4", Text = "Seoul" },               
            };  
  
            //assigning SelectListItem to view Bag  
            ViewBag.cities = cities;  
  
            return View();  
        }  
  
        [HttpGet]  
        public ActionResult InfoBox01(string Value)  
        {  
            List<FoodGet> food = new List<FoodGet>  
            {  
            new FoodGet { Id = "1",  Value = "1", FoodName="Cheese Cake" },  
            new FoodGet { Id = "2",  Value = "1", FoodName="Pizza" },  
            new FoodGet { Id = "3",  Value = "1", FoodName="Hot Dog" },  
            new FoodGet { Id = "4",  Value = "2", FoodName="Spaghetti" },  
            new FoodGet { Id = "5",  Value = "2", FoodName="Carbonara" },  
            new FoodGet { Id = "6",  Value = "3", FoodName="Soba" },  
            new FoodGet { Id = "7",  Value = "4", FoodName="Samgyetang" },  
            new FoodGet { Id = "8",  Value = "4", FoodName="Bulgogi" },  
            };  
              
            return PartialView("InfoBox01", food);  
        }  
  
  
  
  
  
  
  
    }  
}  

Views ( Index.cshtml & InfoBox01.cshtml )

Index.cshtml

<hr />  
<div class="row">  
    <div class="col-md-4">  
        <div class="form-group">  
            <label class="control-label"> Select City</label>  
  
            <select name="products" class="form-control" asp-items="@ViewBag.cities"></select>  
  
  
        </div>  
    </div>  
  
  
    <div id="InfoBox">  
  
        </div>  
  
  
    </div>  
  
  
  
<script type="text/javascript">  
    $(function () {  
  
    }  
  
</script>  

InfoBox01.cshtml

@model IEnumerable<PartialViewWithoutReloadWholePage.Models.FoodGet>  
  
<table>  
    <tr>  
        <td>No&nbsp;&nbsp;&nbsp;</td>  
  
        <td>Id&nbsp;&nbsp;&nbsp;</td>  
        <td>Value&nbsp;&nbsp;&nbsp;</td>  
        <td>Food Name&nbsp;&nbsp;&nbsp;</td>         
    </tr>  
  
    @foreach (var item in Model.Select((x, i) =>  
  new { Data = x, Index = i }))  
    {  
        <tr>  
            <td>@(item.Index + 1)</td>  
  
            <td>@item.Data.Id</td>  
            <td>@item.Data.Value</td>  
            <td>@item.Data.FoodName</td>  
                          
        </tr>  
    }  
</table>  

I need help to display Food Data into this,

   <div id="InfoBox">  
  
        </div>  
  
  
      

And I dont know, how to write script as follow,

<script type="text/javascript">  
    $(function () {  
  
    }  
  
</script>  

Please help. I'm stuck

Developer technologies | ASP.NET | ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2022-03-02T06:56:34.84+00:00

    Hi @Jerry Lipan ,

    Set drop down value to New York (default value), then

    To set the default select value, you can use the SelectListItem.Selected Property, for example, add the Selected property to the "New York" option.

        public IActionResult Index()  
        {        
            //Creating the List of SelectListItem, this list you can bind from the database.  
            List<SelectListItem> cities = new()  
            {  
                new SelectListItem { Value = "1", Text = "New York", Selected = true },  
                new SelectListItem { Value = "2", Text = "Milan" },  
                new SelectListItem { Value = "3", Text = "Tokyo" },  
                new SelectListItem { Value = "4", Text = "Seoul" },  
            };  
            //insert the first option  
            cities.Insert(0, new SelectListItem() { Value = "0", Text = "-- Select City --" });  
    
            //assigning SelectListItem to view Bag  
            ViewBag.cities = cities;   
    
            return View();  
        }  
    

    Partial View ( InfoBox01.cshtml ) automatically display the result

    Then, in the view page, after the document is ready, you can use JQuery to get the Selected value, if the selected value is not the first option ("0"), load the partial view to display the related content.

     <script type="text/javascript">    
         $(document).ready(function(){  
               
             $("#products").change(function () {   
                 $("#InfoBox").load("@Url.Action("InfoBox01")" + "?value=" + this.value);  
             });   
      
             var selectvalue = $("#products").val();  
             if(selectvalue!="0")  
                $("#InfoBox").load("@Url.Action("InfoBox01")" + "?value=" + selectvalue);  
      
         });  
     </script>  
    

    The result is like this:

    179143-1.gif


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Dillion


3 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-02-25T17:25:39.547+00:00

    several issues with your code

    1) the index view should render the partial view inside the inbox div, to handle the preselected value.
    2) typically jquery is included after the view, so $ will not be defined. you should use the script section support
    3) you should specify an id tag on the select say id="products"

    fixing all this, the javascript code is

    $("#products").change(function() {   
         $("InfoBox").load("@Url.Action("InfoBox01")" + "?value=" + this.value);   
    });   
    

    if you don't; want to call the partial from the index, add support for empty value and:

    $(function() {   
      $("#products").change(function() {   
           $("InfoBox").load("@Url.Action("InfoBox01")" + "?value=" + this.value);   
      }).trigger();   
    });   
    
    0 comments No comments

  2. Jerry Lipan 916 Reputation points
    2022-02-26T04:40:12.993+00:00

    Hi @Bruce (SqlWork.com) ,

    After tried, I have this

    177900-ezgifcom-gif-maker.gif

    Controllers ( CityController.cs )

    using Microsoft.AspNetCore.Mvc;  
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Threading.Tasks;  
    using Microsoft.AspNetCore.Mvc.Rendering;  
    using PartialViewWithoutReloadWholePage.Models;  
      
    namespace PartialViewWithoutReloadWholePage.Controllers  
    {  
        public class CityController : Controller  
        {  
            public IActionResult Index()  
            {  
                //Creating the List of SelectListItem, this list you can bind from the database.  
                List<SelectListItem> cities = new()  
                {  
                    new SelectListItem { Value = "1", Text = "New York" },  
                    new SelectListItem { Value = "2", Text = "Milan" },  
                    new SelectListItem { Value = "3", Text = "Tokyo" },  
                    new SelectListItem { Value = "4", Text = "Seoul" },               
                };  
      
                //assigning SelectListItem to view Bag  
                ViewBag.cities = cities;  
      
                return View();  
            }  
      
            [HttpGet]  
            public ActionResult InfoBox01(string Value)  
            {  
                List<FoodGet> food = new List<FoodGet>  
                {  
                new FoodGet { Id = "1",  Value = "1", FoodName="Cheese Cake" },  
                new FoodGet { Id = "2",  Value = "1", FoodName="Pizza" },  
                new FoodGet { Id = "3",  Value = "1", FoodName="Hot Dog" },  
                new FoodGet { Id = "4",  Value = "2", FoodName="Spaghetti" },  
                new FoodGet { Id = "5",  Value = "2", FoodName="Carbonara" },  
                new FoodGet { Id = "6",  Value = "3", FoodName="Soba" },  
                new FoodGet { Id = "7",  Value = "4", FoodName="Samgyetang" },  
                new FoodGet { Id = "8",  Value = "4", FoodName="Bulgogi" },  
                };  
      
                var queryFoods = from _food in food  
                                 where _food.Value == Value  
                                 select _food;  
      
                return PartialView("InfoBox01", queryFoods);  
            }  
      
      
      
      
      
      
      
        }  
    }  
    

    Views ( Index.cshtml )

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
      
    <hr />  
    <div class="row">  
        <div class="col-md-4">  
            <div class="form-group">  
                <label class="control-label"> Select City</label>  
      
                <select  id="products" name="products" class="form-control" asp-items="@ViewBag.cities"></select>  
      
      
            </div>  
        </div>  
    </div>  
      
    <div class="row">  
        <div id="InfoBox">  
      
        </div>  
      
      
    </div>  
      
      
      
    <script type="text/javascript">     
        $("#products").change(function () {  
       
            $("#InfoBox").load("@Url.Action("InfoBox01")" + "?value=" + this.value);  
           }).trigger();  
      
      
    </script>  
    

    Partial View ( InfoBox01.cshtml )

    @model IEnumerable<PartialViewWithoutReloadWholePage.Models.FoodGet>  
      
    <table>  
        <tr>  
            <td>No&nbsp;&nbsp;&nbsp;</td>  
      
            <td>Id&nbsp;&nbsp;&nbsp;</td>  
            <td>Value&nbsp;&nbsp;&nbsp;</td>  
            <td>Food Name&nbsp;&nbsp;&nbsp;</td>         
        </tr>  
      
        @foreach (var item in Model.Select((x, i) =>  
      new { Data = x, Index = i }))  
        {  
            <tr>  
                <td>@(item.Index + 1)</td>  
      
                <td>@item.Data.Id</td>  
                <td>@item.Data.Value</td>  
                <td>@item.Data.FoodName</td>  
                              
            </tr>  
        }  
    </table>  
    

    I need help on - Once Page is Loaded,

    1. Set drop down value to New York (default value), then
    2. Partial View ( InfoBox01.cshtml ) automatically display the result

    177908-26022022-01.png

    Please help

    0 comments No comments

  3. Jerry Lipan 916 Reputation points
    2022-03-04T05:36:05.42+00:00

    Hi @Anonymous

    Masterpiece

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.