遇到了这样的一个需求:通过勾选checkbox来更改select的内容。
在没有勾选checkbox之前是这样的:
在勾选checkbox之后是这样的:
想通过ajax异步来实现。所以,从控制器拿到的json数据,在控制器中应该先是Dictionary<string, string>类型,然后再转换成json格式。
在没有勾选checkbox之前,select中内容对应的Model为:
public class Old{public int Id { get; set; }public string Name { get; set; }}
在勾选checkbox之后,select中内容对应的Model为:
public class NewItem{public int Id { get; set; }public string Name { get; set; }}
Home控制器中应该给出对应的json数据。
public class HomeController : Controller{public ActionResult Index(){return View();}public ActionResult GetOld(){var olds = new List<Old>{new Old(){Id = 1, Name = "老版本1"},new Old(){Id = 2, Name = "老版本2"},new Old(){Id = 3, Name = "老版本3"}};IDictionary<string, string> result = new Dictionary<string, string> {{"-1","None"}};foreach (var item in olds){result.Add(item.Id.ToString(), item.Name);}return Json(result, JsonRequestBehavior.AllowGet);}public ActionResult GetNew(){var news = new List<NewItem>{new NewItem(){Id = 1, Name = "新版本1"},new NewItem(){Id = 2, Name = "新版本2"}};IDictionary<string, string> result = new Dictionary<string, string> { { "-1", "None" } };foreach (var item in news){result.Add(item.Id.ToString(), item.Name);}return Json(result, JsonRequestBehavior.AllowGet);}}
在Home/Index.cshtml视图中,根据checkbox是否勾选来呈现不同的内容。
@{ViewBag.Title = "Index";Layout = "~/Views/Shared/_Layout.cshtml";}<h2>Index</h2><div><select id="v"></select></div><div><span>是否选择新版本:</span><input type="checkbox" id="cn"/></div>@section scripts{<script type="text/javascript">$(function () {//初始获取老版本getOldOnes();//勾选checkbox事件$('#cn').on("change", function() {if ($(this).is(':checked')) {getNewOnes();} else {getOldOnes();}});});//获取老版本function getOldOnes() {$.getJSON('@Url.Action("GetOld","Home")', function(data) {var $s = $('#v');$s.children().remove();$.each(data, function(key, value) {$s.append('<option value="' + key + '">' + value + "</option>");});$s.effect('shake', { times: 4 }, 100);});}//获取新版本function getNewOnes() {$.getJSON('@Url.Action("GetNew","Home")', function (data) {var $s = $('#v');$s.children().remove();$.each(data, function (key, value) {$s.append('<option value="' + key + '">' + value + "</option>");});$s.effect('shake', { times: 4 }, 100);});}</script>}