I am not sure if this jquery script is correct. The Sublist populates on changing main list using where clause on whatever value is selected in main list. Do i need action method? What is the best solution?
<script type="text/javascript">
$("#FKCountyId").change(function () {
$.ajax({
url: "@Url.Action("", "")",
dataType: 'json',
type: 'POST',
data: { txt: $("#FKCountyId").val() },
success: function (data) {
$('#FKCityId').empty();
// need help here
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
View
@Html.LabelFor(m => m.FKCountyId, new { @class = "col-sm-2 col-sm-2 control-label" })
@Html.DropDownListFor(m => m.FKCountyId, Model.GetCounty())
@Html.LabelFor(m => m.FKCityId, new { @class = "col-sm-2 col-sm-2 control-label" })
@Html.DropDownListFor(m => m.FKCityId, Model.GetCity())
Model
public class NewsModel : BaseModel
{
[Required]
public int? FKCountyId { get; set; }
public string County { get; set; }
[Required]
public int? FKCityId { get; set; }
public string City { get; set; }
public List<SelectListItem> GetCounty()
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Please select County", Value = "" });
foreach (var item in LambertonContext.NewsCounties)
{
lst.Add(new SelectListItem() { Text = item.County, Value = item.PKCountyId.ToString() });
}
return lst;
}
public List<SelectListItem> GetCity()
{
List<SelectListItem> lst = new List<SelectListItem>();
lst.Add(new SelectListItem() { Text = "Please select City", Value = "" });
foreach (var item in LambertonContext.NewsCities)
{
lst.Add(new SelectListItem() { Text = item.City, Value = item.PKCityId.ToString() });
}
return lst;
}
}
Your
View
andModel
are not correct, One way to achieve your goal is to create aViewModel
that will handle both of your lists , this way you can leave your base models abstract.Here's how i would rearrange your code.
Model
Controller
and finally your view
EXTRA: You can implement a loading image while the cities DD is getting the data.
Here's a .net fiddle link to a working example