4

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; 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

@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

$('#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);

                    }
                });
            });
3
  • Your partial view is returning html and you're using .html(data) yet you're telling the ajax call that you're expecting json back dataType: 'json', - try removing this line. Commented Apr 27, 2018 at 10:11
  • "but partial is not reflecting the new record" - have you checked the network tab on your browser tools? Have a look at exactly what is being returned. At the very least, add a success: function (data) { console.log(data) and add an error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR, textStatus, errorThrown); } to show any errors. Commented Apr 27, 2018 at 10:13
  • 1
    @freedomn-m, Thank you so much. When I removed dataType: 'json', it worked for me. Commented Apr 27, 2018 at 10:25

2 Answers 2

3

When requesting partial views from MVC, you are returning HTML rendered on the server, so your ajax request must not be requesting 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'

Giving:

$.ajax({
    url: '@Url.Action("PartialView", "Home")',
    type: 'POST',
    data: JSON.stringify({ countrylist: countrylist }),
    contentType: 'application/json',
    success: function (data) {
        $("#mypartial").html(data);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much @freedomn-m. It solved my problem.
1

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);
        }
    });
}); 

6 Comments

Yes there was typo. I fixed that and also removed dataType: 'json'. It worked for me now. In your answer, please mention to remove it. I will accept it after then. Thank you for your time.
I have updated the answer. Either you can remove datatype or you can specify it as text both will work
It does not work if I add datatype and contentType: 'application/text; charset=utf-8',. It does not give me anything. But If I remove content type and specify contentType: 'application/json', then it works for me.
It will work in a get request. since your's is a post so you have to remove datatype:json
Thank you for your time @kritika.@freedomn-m answer worked for me.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.