In ASP. net mvc, select checkbox to change the select content.
The following requirement is met: You can check the checkbox to change the select content.
Before checkbox is checked, it is as follows:
After checking the checkbox, it is as follows:
It is implemented asynchronously through ajax. Therefore, the json data obtained from the Controller should first be of the Dictionary <string, string> type in the controller, and then be converted to the json format.
The Model corresponding to the content in the select statement is:
public class Old
{
public int Id { get; set; }
public string Name { get; set; }
}
After checking the checkbox, the Model corresponding to the content in the select statement is:
public class NewItem
{
public int Id { get; set; }
public string Name { get; set; }
}
The corresponding json data should be provided in the Home controller.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult GetOld()
{
var olds = new List<Old>
{
New Old () {Id = 1, Name = "Old Version 1 "},
New Old () {Id = 2, Name = "Old Version 2 "},
New Old () {Id = 3, Name = "Old Version 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 = "new Version 1 "},
New NewItem () {Id = 2, Name = "new Version 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);
}
}
In the Home/Index. cshtml view, different content is displayed based on whether or not the checkbox is checked.
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
<select id="v"></select>
</div>
<div>
<Span> whether to select a new version: </span> <input type = "checkbox" id = "cn"/>
</div>
@section scripts
{
<script type="text/javascript">
$(function () {
// Obtain the old version
getOldOnes();
// Check the checkbox event
$('#cn').on("change", function() {
if ($(this).is(':checked')) {
getNewOnes();
} else {
getOldOnes();
}
});
});
// Obtain the old version
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);
});
}
// Obtain the new version
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>
}