我正在编写一个 ASP.NET MVC 4 应用程序。我对网络编程环境比较陌生;我想我已经掌握了模型和 Controller 部分的要点,包括存储库和工作单元模式。但我在客户端的事情上迷失了。假设我的 Controller 中有这个操作方法:
//I have a Brand table in my Entity framework model
public ActionResult GetBrands()
{
var result = _unitOfWork.BrandRepository.GetBrands();
return Json(result, JsonRequestBehavior.AllowGet);
}
我对 Javascript、Ajax 和 JQueryUI 很迷茫。我在主视图 (Index.cshtml) 中创建了一个静态 JQueryUI 选择菜单:
<select name="brands" id="brands">
<option>Brand1</option>
<option>Brand2</option>
<option selected="selected">Brand3</option>
<option>Brand4</option>
<option>Brand5</option>
</select>
如何调用操作方法来用品牌填充选择菜单?
最佳答案
由于我不知道“BrandRepository”的内容是什么,所以这是一个笼统的答案。
如果您设置使用 jquery 和 json 填充它,这是一个示例:
<script type="text/javascript">
$(function() { //only call when the DOM is ready
alert('DOM is ready!');
$.getJSON("/MyController/GetBrands/", function(result) {
alert('The controller action got hit successfully');
var options = $("#brands");
options.html(''); //clears the current options
alert('The result was: ' + JSON.stringify(result));
$.each(result, function(i, item) {
options.append('<option id="' + item.Id + '">' + item.Name '</option>');
});
});
});
</script>
这假设品牌由有效 json 中的 Id 和 Name 组成。
关于javascript - 从数据库填充 JQueryUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29241773/