这是我的控制器类:
public class TestController : Controller
{
log4net.ILog _logger = log4net.LogManager.GetLogger(typeof(HomeController));
//
// GET: /Test/
public ActionResult Index()
{
List<SelectListItem> testlist = new List<SelectListItem>();
SelectListItem s = new SelectListItem();
s.Value = "--Select One--";
s.Text = "--Select One--";
testlist.Add(s);
ViewBag.Items = testlist;
return View();
}
public ActionResult PassToView()
{
List<SelectListItem> testlist = new List<SelectListItem>();
SelectListItem s = new SelectListItem();
s.Text = "data1";
s.Value = "data1";
testlist.Add(s);
s = new SelectListItem();
s.Text = "data2";
s.Value = "data2";
testlist.Add(s);
s = new SelectListItem();
s.Text = "data3";
s.Value = "data3";
testlist.Add(s);
s = new SelectListItem();
s.Text = "data4";
s.Value = "data4";
testlist.Add(s);
s = new SelectListItem();
s.Text = "data5";
s.Value = "data5";
testlist.Add(s);
return Json(testlist, JsonRequestBehavior.AllowGet);
}
public ActionResult PassToController(string SelectedValue)
{
_logger.Info("Selected value is :" + SelectedValue);
return View();
}
}
这是我的观点:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.DropDownList("ddlItems", (IEnumerable<SelectListItem>)ViewBag.Items, new { @id = "ddlItems", @class = "dropdownlist", onchange = "ddlItemChange();" })
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Test/PassToView", function (data) {
var selectList = $("#ddlItems");
selectList.empty();
$.each(data, function (index, optionData) {
var option = $('<option>').text(optionData.Text).val(optionData.Value);
selectList.append(option);
});
selectList.trigger("chosen:updated");
});
});
function ddlItemChange() {
var selectedvalue = $("select[name='ddlItems']").val();
$.post("/Test/PassToController", { SelectedValue: selectedvalue });
return false;
}
</script>
下拉列表未填写。请参阅附图。
你可以告诉我我做错了吗? 谢谢你的时间。