Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hey guys have this;I took it in a article , my project is quite similar
but this show a list of states in another dropdownList, what can I do to change this project under to show the states in a <table> ???
can anyone help me ?

JavaScript
<script type="text/javascript">
    $(function () {
        $("#CountryId").change(function () {
            var selectedItem = $(this).val();
            var ddlStates = $("#StateId");
            var statesProgress = $("#states-loading-progress");
            statesProgress.show();
            $.ajax({
                cache: false,
                type: "GET",
                url: "@(Url.RouteUrl("GetStatesByCountryId"))",
                data: { "countryId": selectedItem },
                success: function (data) {


                    ddlStates.html('');
                    $.each(data, function (id, option) {
                        ddlStates.append($('<option></option>').val(option.id).html(option.name));

                    //ddlStates.html('');
                    //$.each(data, function (id, label) {
                    //    ddlStates.append($('<label></label>').val(label.id).html(label.name));

                    });
                    statesProgress.hide();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve states.');
                    statesProgress.hide();
                }
            });
        });
    });
</script>


HTML
@Html.LabelFor(model => model.CountryId)
@Html.DropDownListFor(model => model.CountryId, Model.AvailableCountries)

<br />

@Html.LabelFor(model => model.StateId)
    @Html.DropDownListFor(model => model.StateId, Model.AvailableStates)

        <span id="states-loading-progress" style="display: none;">Please wait..</span>
Posted
Updated 13-Nov-14 23:56pm
v2
Comments
Nathan Minier 14-Nov-14 7:02am    
If I understand you correctly, you want to dynamically load a table with states/territories based on the country selected, correct?
Member 11233046 14-Nov-14 9:18am    
yeah Nathan that´s right ...
on the same page when I selected the country
please help me

1 solution

A couple things, if you have a repository model, don't put a DbContext on your controller (you're wasting cycles if you do). We had a misunderstanding about where code lay in specific places, so I'm trying to be more specific here.

I'm going to go ahead, build and test, but this should be a total solution for this module, which is normally a bit more than folks are looking at in quick answers.

I've run and validated the code, it works just fine as is.

AddressModel.cs
C#
public class AddressModel
{
   public int CountryId { get; set; }
 
   [Display(Name = "Country")]
   public IList<SelectListItem> AvailableCountries { get; set; }
 
   [Display(Name = "State")]
   public int StateId { get; set; }
 
   public IList partialModel { get; set; }
 
   public AddressModel()
   {
      AvailableCountries = new List<SelectListItem>();
   } 
}


AddressRepository.cs
C#
public class AddressRepository
    {
        public Entities db = new Entities();

        public IList<Country> GetAllCountries()
        {
            return db.Countries.ToList();
            ;
        }

        public IList<State> GetAllStatesByCountryId(int countryId)
        {
            return db.States.Where(x => x.Country_Id == countryId).ToList();
        }
    }


AddressController.cs
C#
public class AddressController : Controller
    {
        private AddressRepository _repository1 { get; set; }

        public AddressController()
            : this(new AddressRepository())
        {
        }

        public AddressController(AddressRepository repository)
        {
            _repository1 = repository;
        }

        public ActionResult Index()
        {
            var model = new AddressModel();
            model.AvailableCountries.Add(new SelectListItem
            {
                Text = "-Please select-",
                Value = "Selects items"
            });
            var countries1 = _repository1.GetAllCountries();
            foreach (var country in countries1)
            {
                model.AvailableCountries.Add(new SelectListItem()
                {
                    Text = country.Name,
                    Value = country.Id.ToString()
                });
            }
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetStates(int countryId)
        {
            if (countryId == 0)
            {
                throw new ArgumentException("countryId");
            }
            return PartialView(_repository1.GetAllStatesByCountryId(countryId));
        }
    }



index.cshtml
C#
@model FarControl.Models.AddressModel

@{
    ViewBag.Title = "Index";
}

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
        $('#CountryId').change(function () {
            var selectedItem = $(this).val();
            var statesProgress = $('#states-loading-progress');
            statesProgress.show();
            $.ajax({
                cache: false,
                type: 'GET',
                url: '@(Url.Action("GetStates"))',
                data: { 'countryId': selectedItem },
                success: function (data) {
                    $('#tableStates').html(data);
                    statesProgress.hide();
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert('Failed to retrieve states.');
                    statesProgress.hide();
                }
            });
        });
    });
</script>

@Html.LabelFor(model => model.CountryId)
@Html.DropDownListFor(model => model.CountryId, Model.AvailableCountries)

<br />
<div id="tableStates"></div>

<span id="states-loading-progress" style="display: none;">Please wait..</span>



GetStates.cshtml
C#
@model IEnumerable<State>

@if (Model != null)
{
   <table>
   @foreach (var state in Model)
   {
      //Add appropriate properties to table from the STATE object
      <tr><td>@state.Name</td></tr>
   }
   </table>
}
 
Share this answer
 
v9
Comments
Member 11233046 15-Nov-14 5:01am    
Nathan thanks you help . . . it seems work, but I still have some issues... I can´t handle your code with mine...
on controller . . .
I have this
public class AddressController : Controller
{
Entities db = new Entities();

private IAddressRepository _repository1;

public AddressController()
: this(new AddressRepository())
{
}

public AddressController(IAddressRepository repository)
{
_repository1 = repository;
}



public ActionResult Index()
{
AddressModel model = new AddressModel();
model.AvailableCountries.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
var countries1 = _repository1.GetAllCountries();
//var countries = _repository.GetAllCountries();
foreach (var country in countries1)
{
model.AvailableCountries.Add(new SelectListItem()
{
Text = country.Name,
Value = country.Id.ToString()
});
}
return View(model);
}

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetStatesByCountryId(string countryId)
{
if (String.IsNullOrEmpty(countryId))
{
throw new ArgumentNullException("countryId");
}
int id = 0;
bool isValid = Int32.TryParse(countryId, out id);
var states = _repository1.GetAllStatesByCountryId(id);
var result = (from s in states
select new
{
id = s.Id,
name = s.Name
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
}}
on my model . . .
<pre lang="sql">public class AddressModel
{
public AddressModel()
{
AvailableCountries = new List<SelectListItem>();
AvailableStates = new List<SelectListItem>();
}
public int CountryId { get; set; }
[Display(Name = "Country")]
public IList<SelectListItem> AvailableCountries { get; set; }
[Display(Name = "State")]
public int StateId { get; set; }
public IList<SelectListItem> AvailableStates { get; set; }
}</pre>
<pre lang="xml">public interface IAddressRepository
{
IList<Country> GetAllCountries();
IList<State> GetAllStatesByCountryId(int countryId);
}</pre>
<pre lang="xml">public class AddressRepository : IAddressRepository
{
Entities db = new Entities();

public IList<Country> GetAllCountries()
{
var query = from Countries in db.Countries
select Countries;
var content = query.ToList<Country>();
return content;
}
public IList<State> GetAllStatesByCountryId(int countryId)
{
var query = from States in db.States
where States.Country_Id == countryId
select States;
var content = query.ToList<State>();
return content;

}

}</pre>
can you give a word ? "I´m totally new, but I have to do this"
Nathan Minier 17-Nov-14 7:14am    
You need to switch out the GetAllStatesByCountryId for the GetStates function I put in my answer. Then you'll need to build a template partialview to handle the state data, that's the only issue I'm seeing.
Member 11233046 18-Nov-14 4:38am    
I did this on controller like you said
public ActionResult GetStates(string countryId)
{
int id = 0;
bool isValid = Int32.TryParse(countryId, out id);
IEnumerable<string> list = (from States in db.States
where States.Country_Id == id select States);
return PartialView(list);
}
on my view I can do that @model IEnumerable<string> because my main view is of type @model FarControl.Models.AddressModel as I put above

my deadline is closing
Nathan Minier 18-Nov-14 7:04am    
So your razor view will have @model IEnumerable<FarControl.Models.AddressModel>

And access the properties in the table:
<table>
@foreach(var state in Model)
{
<tr>
<td>state.Property1</td><td>state.Property1</td>
</tr>
}
</table>

Change the property names for whatever are appropriate.
Member 11233046 18-Nov-14 7:26am    
Get states on my controller , like you said , there´s a error, when I put IEnumerable<string> list . . . appear a error on sql instruction , even IEnumerable<addressmodel>that I think the right way... I resolve it putting IEnumerable<states> list... doing that I have to change the razor view to @model FarControl.Models.AddressModel did you get ???

public ActionResult GetStates(string countryId)
{
int id = 0;
bool isValid = Int32.TryParse(countryId, out id);
IEnumerable<states> list = (from States in db.States
where States.Country_Id == id select States);
return PartialView(list);
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900