简体   繁体   English

如何使用AJAX在下拉列表中根据选项更改调用局部视图?

[英]How to call partial view based on option change in dropdown using AJAX?

I have created parent view and partial view. 我创建了父视图和部分视图。 In parent view, I have country dropdownlist. 在父视图中,我有国家/地区下拉列表。 And it also shows partial view. 它也显示了局部视图。 When the page loads, it displays both dropdownlist and partial view list. 页面加载时,它会显示下拉列表和部分视图列表。

What I want is that, When I change the option in dropdownlist, the partial view displays based on the option selected. 我想要的是,当我更改下拉列表中的选项时,部分视图将根据所选的选项显示。

I tried this code but no luck so far. 我试过这段代码,但到目前为止没有运气。 I have pasted all the code which I tried. 我已经粘贴了我尝试过的所有代码。 I am getting the data in return clsStakes; 我收到的数据是return clsStakes; if I change in dropdown but partial is not reflecting the new record. 如果我改变了下拉但是部分没有反映新记录。

Please guide me. 请指导我。

My modal 我的模态

   public class clsStakes
    {
        public string Country { get; set; }
    }

    public class ClsPartialStackes
    {
        public string Date { get; set; }
        public string Race { get; set; }
    }

Controller 调节器

public class HomeController : Controller
{

   [HttpGet]
   public ActionResult Home()
    {         
        return View();
    }       

    // Display Partial View
    public ActionResult PartialView(string countrylist, clsStakes clsStakes)
    {
        if(countrylist==null)
        {
            clsStakes.Country = "IRE";
        }
        else
        {
            clsStakes.Country = countrylist;
        }

        StakesDetails stakesDetails = new StakesDetails();
       return PartialView("~/Views/Stakes/_PartialStakes.cshtml", stakesDetails.StacksList(clsStakes.Country));

    }

}

View 视图

@model AAA.Website.Models.Stakes.clsStakes
@Html.DropDownListFor(m => m.Country, new List<SelectListItem>
 {
     new SelectListItem {Value = "IRE", Text="Ireland" },
     new SelectListItem {Value = "ITY", Text = "Italy"},
     new SelectListItem {Value = "JPN", Text = "Japan" },
     new SelectListItem {Value = "NZ", Text = "New Zealand" },

  },
    new {@id="CountryList", @class = "form-control" })          

 <div id="mypartial"> </div>

Method to call the procedure to load list of items in partial 调用过程以加载部分项目列表的方法

public class StakesDetails
    {
        clsUtilities clsUtilities = new clsUtilities();
        DataSet ds;
        public List<ClsPartialStackes> StacksList(string Country)
        {
            List<ClsPartialStackes> clsStakes = new List<ClsPartialStackes>();

            SqlParameter[] prms = new SqlParameter[1];
            string sSQL;
            sSQL = "exec GetStakes @Country";
            prms[0] = new SqlParameter("@Country", SqlDbType.VarChar);
            prms[0].Value = Country;
            ds = clsUtilities.CreateCommandwithParams(sSQL, prms);        
            DataTable dataTable = ds.Tables[0];
            foreach (DataRow dr in dataTable.Rows)
            {
                clsStakes.Add(
                    new ClsPartialStackes
                    {
                        Date = Convert.ToString(dr["mdate"]),                    
                        Race = Convert.ToString(dr["racename"]),                   
                    });
            }
            return clsStakes;
        }


    }

Script to load the partial 脚本加载部分

 $(document).ready(function () {
    var route = '@Url.Action("PartialView", "Home")';
     route = encodeURI(route);
     $('#mypartial').load(route);
    });

PartialView PartialView

@model IEnumerable<AAA.Website.Models.Stakes.ClsPartialStackes>


<table>
    <tr>
        <th>@Html.DisplayNameFor(m => m.Date)</th>
        <th>@Html.DisplayNameFor(m=>m.Race)</th>    
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Date)
            </td>
            <td>
              @Html.DisplayFor(modelItem => item.Race)               
            </td>         
        </tr>
    }
</table>

Script to call partial based on change in dropdown 根据下拉列表中的更改调用partial的脚本

$('#CountryList').change(function () {
         var countrylist = $(this).val();
                $.ajax({
                     url: '@Url.Action("PartialView", "Home")',
                     type: 'POST',
                    data: JSON.stringify({ countrylist: countrylist }),
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function (data) {
                        $("#mypartial").html(data);

                    }
                });
            });

When requesting partial views from MVC, you are returning HTML rendered on the server, so your ajax request must not be requesting json: 从MVC请求部分视图时,您将返回在服务器上呈现的HTML,因此您的ajax请求不得请求json:

$.ajax({
    url: '@Url.Action("PartialView", "Home")',
    type: 'POST',
    data: JSON.stringify({ countrylist: countrylist }),
    dataType: 'json',
    contentType: 'application/json',
    success: function (data) {
        $("#mypartial").html(data);
    }
});

remove the line: 删除行:

    dataType: 'json',

or change it to 'html' 或将其更改为'html'

Giving: 赠送:

$.ajax({
    url: '@Url.Action("PartialView", "Home")',
    type: 'POST',
    data: JSON.stringify({ countrylist: countrylist }),
    contentType: 'application/json',
    success: function (data) {
        $("#mypartial").html(data);
    }
});

there is a typo in your code at: 您的代码中有一个拼写错误:

 $("#mypartial".html(data);

and also change datatype and content type to 并将数据类型和内容类型更改为

$('#CountryList').change(function () {
    var countrylist = $(this).val();
    $.ajax({
        url: '@Url.Action("PartialView", "Home")',
        type: 'POST',
        data: JSON.stringify({ countrylist: countrylist }),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
           $("#mypartial").html(data);
        }
    });
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM