Jquery 将Json结果绑定到MVC4中的DropDownlist
我试图在mvc4中实现一个级联dropdownlist。我对第一个dropdownlist使用字典值,对第二个dropdownlist使用绑定xml值。根据国家的选择(第一个DDL),必须加载状态(第二个DDL)。如何使用jQuery将jsonresult绑定到第二个dropdownlist。JsonResult在firebug中返回良好。我的剧本有什么错误。任何建议都会大有帮助 这是我的代码。Jquery 将Json结果绑定到MVC4中的DropDownlist,jquery,asp.net-mvc,json,asp.net-mvc-4,html.dropdownlistfor,Jquery,Asp.net Mvc,Json,Asp.net Mvc 4,Html.dropdownlistfor,我试图在mvc4中实现一个级联dropdownlist。我对第一个dropdownlist使用字典值,对第二个dropdownlist使用绑定xml值。根据国家的选择(第一个DDL),必须加载状态(第二个DDL)。如何使用jQuery将jsonresult绑定到第二个dropdownlist。JsonResult在firebug中返回良好。我的剧本有什么错误。任何建议都会大有帮助 这是我的代码。 查看 @using (Html.BeginForm("Details", "WPWebGridCar
查看
@using (Html.BeginForm("Details", "WPWebGridCart", new { userID = Request.QueryString["UserID"], partnerid = Request.QueryString["Partnerid"] }, FormMethod.Post))
{
if (Model.Count() == 0)
{
@Html.DisplayNameFor(model => model.Country)
@{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
dictionary.Add("USA", "USA");
dictionary.Add("UK", "UnitedKingdom");
dictionary.Add("India", "India");
SelectList list = new SelectList(dictionary, "value", "key", "India");
}
@Html.DropDownList("Country", list, "(Select Country)", new { @class = "TextBoxBorder" })
@Html.DisplayNameFor(model => model.State)
@if (ViewData["PageOptions"] != null)
{
@Html.DropDownList("State", ViewData["PageOptions"] as IEnumerable<SelectListItem>, "(Select one)", new { @class = "TextBoxBorder" })
}
else
{
<select id="State" name="State" class="TextBoxBorder">
</select>
}
}
else
{
// design
}
}
对我也犯了同样的错误。现在它工作得很好。谢谢达林:)-
$(document).ready(function () {
$("#Country").change(function () {
var selection = $("#Country").val();
var dataToSend = {
country: selection
};
$.ajax({
type: "GET",
url: "/WPWebGridCart/GetStateDetails/",
data: dataToSend,
success: function (data) {
$('#State').append('<option value="' + agent + '">' '</option>');
}
});
});
});
public JsonResult GetStateDetails(string country)
{
var file = Path.Combine(Server.MapPath("~/App_Data"), "States.xml");
var model = new CheckoutModel
{
States =
from unit in XDocument.Load(file)
.Descendants("Capital")
.First(unit => (string)unit.Attribute("CountryName") == country)
.Descendants("city")
select new SelectListItem
{
Text = unit.Attribute("name").Value,
Value = unit.Attribute("value").Value,
}
};
SelectList selectList = new SelectList(model.States, "Value", "Text");
ViewData["PageOptions"] = selectList;
return Json(new { agent = ViewData["PageOptions"] }, JsonRequestBehavior.AllowGet);
}
$('#State').append('<option value="' + agent + '">' '</option>');
success: function (data) {
var statesDdl = $('#State');
statesDdl.empty();
$.each(data.agent, function() {
statesDdl.append(
$('<option/>', {
value: this.Value,
html: this.Text
})
);
});
}