【问题标题】:Populate JQueryUI from database从数据库填充 JQueryUI
【发布时间】:2015-03-24 20:00:06
【问题描述】:

我正在编写一个 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>

如何调用我的操作方法来用品牌填充选择菜单?

【问题讨论】:

  • 仅供参考:您不是在填充“jQueryUI”,而是在填充普通的 html 选择列表/下拉列表。您可能希望使用 jQuery 填充选择列表,并使用 jQueryUI 对其进行样式设置。实际上,您可能只想通过将模型传递给视图来填充选择,但这还有待观察:)
  • 别管造型,我只想用模型中的数据填充它。如果我有时间,我会让它更漂亮

标签: javascript asp.net-mvc jquery-ui razor


【解决方案1】:

由于我不知道“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 中的 IdName 组成。

【讨论】:

  • DOM 准备好后如何调用它?我尝试在几个地方粘贴它,但它没有渲染任何东西
  • @dario_ramos 脚本中的第一行确保它在准备好时被调用。我猜你已经在 _Layout 文件中包含了 jQuery?只需将此脚本放在同一文件中即可。我将使用一些“调试警报”更新示例,以便您了解它的进展情况。
猜你喜欢
  • 2010-09-26
  • 2012-06-25
  • 2011-07-01
  • 2021-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
  • 2012-07-22
相关资源
最近更新 更多