https://dotnetfiddle.net/hWKzMo, Ваш просмотр:
@{
Layout = null;
}
<!DOCTYPE html>
@*credit to https://stackoverflow.com/questions/51525958/dropdownlist-with-java-script*@
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut118</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGetNew").click(function () {
var theData = $('#thePassedData').val();
var passMe = { passedData: theData };
$.ajax({
type: "POST",
url: "/Home/GetDataButDontOverrwite",
data: passMe,
dataType: 'json',
success: function (data) {
$.each(data, function (i, anObj) {
$("#TheDropDown").append($('<option>').text(anObj.Text).attr('value', anObj.Value));
});
}
});
})
})
</script>
</head>
<body>
<div>
<input type="hidden" id="thePassedData" value="2" />
<input type="button" id="btnGetNew" value="GetNew" />
<p />
This dropdown initally contains values and when you 'GetNew', it adds more values
<p />
@Html.DropDownList("TheDropDown", ViewBag.Drop as List<SelectListItem>)
<p />
The above dropdown, text, and button are part of the old page, and when you click on 'GetNew',
new values will be added to the page, but the new values will NOT overrite the old value
</div>
</body>
</html>
Ваш контроллер / модель просмотра:
public class passMe
{
public string passedData { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public string GetDataButDontOverrwite(passMe passMe)
{
var drop2 = new List<SelectListItem>();
SelectListItem sli1 = new SelectListItem { Text = "MoreOptions1", Value = "MoreOptions1" };
SelectListItem sli2 = new SelectListItem { Text = "MoreOptions2", Value = "MoreOptions2" };
drop2.Add(sli1);
drop2.Add(sli2);
//You need Newtonsoft.JSON
return JsonConvert.SerializeObject(drop2);
}
public ActionResult Tut118()
{
List<SelectListItem> drop = new List<SelectListItem>();
SelectListItem sli1 = new SelectListItem { Selected = true, Text = "Option1", Value = "Option1" };
SelectListItem sli2 = new SelectListItem { Text = "Option2", Value = "Option2" };
drop.Add(sli1);
drop.Add(sli2);
ViewBag.Drop = drop;
return View();
}