【问题标题】:Partial View using a Model, update it with Ajax使用模型的部分视图,使用 Ajax 更新它
【发布时间】:2012-09-11 21:47:33
【问题描述】:

我有一个使用模型的局部视图。 部分视图是空的,除了一个文本框和一个按钮。

用户将在文本框中输入一个值并单击按钮。

我想使用 Ajax 获取在文本框中输入的值,并在数据库中执行搜索。然后使用返回的数据,使用 Model 更新 Partial View。

到目前为止我的代码 -

<input id="searchValue" type="text" />   
<input id="searchButton" type="submit" value="submit" />

<div>
@if(Model != null)
{
    foreach(var stuff in Model.ListOfStuff)
    {
        <li>@stuff.value</li>  
    }
}
</div>

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: ajax asp.net-mvc model asp.net-mvc-partialview


    【解决方案1】:

    本文将为您提供帮助,只需按照他们的做法并将他们的概念应用到您的代码中:Updating Partial Views with Unobtrusive AJAX in MVC 3

    【讨论】:

      【解决方案2】:

      为您的 Result Div 提供一个 ID,以便我们稍后通过 jQuery 进行更新。

      <div id="resultDiv">
          <ul></ul>
      </div>
      

      现在添加这个javascript代码

      $(function(){
        $("#searchButton").click(function(e){
           var key=$("#searchKey").val();
           $.getJSON("@Url.Action("search","Items")/"+key,function(data){
              var items="";
              $.each(data,function(index,item){
                  items+="<li>"+item.Name+"</li>;
              });
              $("#resultDiv>ul").html(items);
           });
        });
      });
      

      现在我们应该有一个动作方法,它接受搜索键并以 JSON 格式返回结果。

      public ActionResult Search(string id)
      {
        List<Product> productList=repo.GetSearchResultFromKey(id);
        return Json(productList,JsonRequestBehaviour.AllowGet);
      }
      

      假设我们有一个名为 Product 的视图模型,如下所示,并且我们的 GetSearchResultFromKey 方法从我们的搜索键返回 Product 类的集合。

      public class Product
      {
        public string Name { set;get;}
      }
      

      我们在这里所做的是,当用户点击搜索按钮时,我们获取搜索键并调用搜索操作方法,该方法将返回JSON格式的产品列表。我们正在遍历 JSON 响应中的项目并创建 li 项目并将其添加到 ul 元素中。

      确保页面中包含 jQuery。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-26
        • 1970-01-01
        相关资源
        最近更新 更多