【发布时间】:2014-08-11 14:53:24
【问题描述】:
我想知道我是否有可能从 MVC 中的嵌套下拉列表中发布文本值??
我已经能够使用我的数据库值填充下拉列表,并且当它选择第一个下拉列表时,它会自动使用 json 结果填充第二个下拉列表。我想从下拉列表中发布文本值,可以吗??
这是我的带有 JSON 调用的控制器
[HttpPost]
public ActionResult Index(SchoolRegViewModel model, HttpPostedFileBase Logo)
{
var queryCountry = _countryState.GetAllCountry().Select(s => new SelectListItem
{
Value = s.CountryId.ToString(),
Text = s.CountryName,
Selected = false
});
model.Country = queryCountry.AsEnumerable();
var country = model.Country.Select(x => x.Text).Single();
if (ModelState.IsValid)
{
try
{
....
}
catch (Exception ex)
{
throw ex;
}
}
return View(model);
}
public JsonResult StateList(int? id)
{
if (id != null)
{
var state = _countryState.GetAllState(id.Value);
return Json(new SelectList(state, "CountryId", "StateName"), JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { }, JsonRequestBehavior.AllowGet);
}
}
这是我的 jquery,用 json 结果填充第二个下拉列表
jQuery(function ($) {
$(function ()
{
$('#CountryId').change(function () {
$.getJSON('/Registration/Registration/StateList/' + $('#CountryId').val(), function (data) {
var items = '<option>-- Select State --</option>';
$.each(data, function (i, state) {
items += "<option value = '" + state.Value + "'>" + state.Text + "</option>";
});
$('#State').html(items);
$('#State option:selected').text();
});
});
});
});
查看
<div class="control-group">
<label for="text" class="control-label">Country</label>
<div class="controls">
@Html.DropDownListFor(model => model.CountryId, Model.Country, "-- Choose Country --", new { id = "CountryId", required="true"})
</div>
</div>
<div class="control-group">
<label for="text" class="control-label">State/Provinces</label>
<div class="controls">
<select name="State" id="State" data-rule-required="true">
</select>
</div>
</div>
【问题讨论】:
标签: javascript jquery asp.net-mvc json drop-down-menu