我正在写一个ASP。NET MVC 4应用程序。我对网络编程环境比较陌生;我想我已经了解了模型和控制器部分的要点,包括存储库和工作单元模式。但我迷失在客户方面。假设我的控制器中有这样的操作方法:
//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组成。