jquery 或 javascript 中是否有一种方法可以在不使用 ajax 请求的情况下在页面加载时填充下拉列表?
Is there a way in jquery or javascript to populate dropdown lists on page load without using an ajax request?
我想在页面加载时使用 jQuery 填充一些下拉列表,而不是使用 ajax 响应我目前正在处理的事件。
我的控制器为这些下拉菜单构建了几个列表对象。
目前我使用 ajax 和我的操作 return 数据,但这在呈现时需要在我的视图中。
C#代码:
return Json(ddlVals1, JsonRequestBehavior.AllowGet)
return Json(ddlValAnother, JsonRequestBehavior.AllowGet)
我希望在 jQuery 代码中执行的示例;
$(function ()
{
LoadUserDropDown();
LoadAnotherDropDown();
});
谢谢。
只要传递列表值就可以查看。例如,可以使用ViewBag将临时数据传输到View。
// Action
public ActionResult Index()
{
ViewBag.FirstDropDownList = new List<string>() { "Item 1", "Item 2" };
ViewBag.FirstDropDownListJson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.FirstDropDownList);
return View("Index");
}
// View using razor
<select>
@foreach(var item in ViewBag.FirstDropDownList)
{
<option value="@item">@item</option>
}
</select>
// View using jQuery
<select id="dropdown1"></select>
<script>
$(function(){
var dropdown1List = JSON.parse('@Html.Raw(ViewBag.FirstDropDownListJson)');
$('#dropdown1').html($.map(dropdown1List, a => `<option value="${a}">${a}</option>`));
});
</script>
我想在页面加载时使用 jQuery 填充一些下拉列表,而不是使用 ajax 响应我目前正在处理的事件。 我的控制器为这些下拉菜单构建了几个列表对象。 目前我使用 ajax 和我的操作 return 数据,但这在呈现时需要在我的视图中。
C#代码:
return Json(ddlVals1, JsonRequestBehavior.AllowGet)
return Json(ddlValAnother, JsonRequestBehavior.AllowGet)
我希望在 jQuery 代码中执行的示例;
$(function ()
{
LoadUserDropDown();
LoadAnotherDropDown();
});
谢谢。
只要传递列表值就可以查看。例如,可以使用ViewBag将临时数据传输到View。
// Action
public ActionResult Index()
{
ViewBag.FirstDropDownList = new List<string>() { "Item 1", "Item 2" };
ViewBag.FirstDropDownListJson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.FirstDropDownList);
return View("Index");
}
// View using razor
<select>
@foreach(var item in ViewBag.FirstDropDownList)
{
<option value="@item">@item</option>
}
</select>
// View using jQuery
<select id="dropdown1"></select>
<script>
$(function(){
var dropdown1List = JSON.parse('@Html.Raw(ViewBag.FirstDropDownListJson)');
$('#dropdown1').html($.map(dropdown1List, a => `<option value="${a}">${a}</option>`));
});
</script>