【问题标题】:Data not loaded in table using ajax in ASP.net mvc在 ASP.net mvc 中使用 ajax 未将数据加载到表中
【发布时间】:2013-12-26 11:27:11
【问题描述】:

我想在 ASP.net mvc 中使用 Ajax 检索 html 表中的数据,但成功部分没有执行,并且不知道如何使用 Ajax 在表中显示返回的数据。请提出任何解决此问题的方法。谢谢。。

索引.cshtml

@model IEnumerable<MvcApplication4.Models.tbl_product>
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
    <title>Index</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#Button1').click(function () {
                alert("button clicked");
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    url: 'Home/Index',
                    data: "{'searchString':'" + document.getElementById('searchString').value + "'}",
                    async: false,
                    Success: function (response) {
                        alert("Success");
                        window.location.reload();
                    },
                    error: function () { alert("error"); }
                });

            });
        });
    </script>
</head>
<body>

    @Html.TextBox("searchString");
    <input type="button" value="filter" id="Button1" />
    <table id="showData">
        @{Html.RenderPartial("SearchList");}
    </table>
</body>
</html>

HomeController.cs

 public class HomeController : Controller
    {
        //
        // GET: /Home/
        ProductEntities dbentity = new ProductEntities();
        public ActionResult Index()
        {
            return View(dbentity.tbl_product.ToList());
        }

        [HttpPost]
        public ActionResult Index(string searchString)
        {
            var query = dbentity.tbl_product.Where(c => c.ProductName.Contains(searchString));
            return View(query.ToList());
        }
    }

SearchList.cshtml

@foreach (var item in Model)
{ 
<tr>
<td>@item.ProductName</td>
<td>@item.ProductId</td>
<td>@item.ProductDesc</td>
</tr>
}

【问题讨论】:

  • 首先是success而不是Success
  • 它抛出了什么错误。是否在控制器中触发操作
  • 并且在你的ajax调用中也包含dataType:'json';
  • 现在更改为小写后,成功部分正在执行,但是我将如何将数据搜索附加到表中,我可以在 OnBlur 事件上调用 ajax 函数而不是单击按钮...谢谢以上建议....

标签: jquery asp.net ajax asp.net-mvc asp.net-mvc-3


【解决方案1】:
  1. 它的success 不是Success
  2. 您需要返回部分视图
  3. 您需要使用返回的部分视图更新table HTML

将您的代码更改为

success: function (response) {
    alert("Success");
    $('#showData').html(response)
},

控制器代码

 return PartialView("SearchList", query.ToList());

如果您不提供ViewName,按照惯例它将使用ActionName 作为视图名称。因此将SearchList 传递为ViewName

编辑:

另外,你需要传递模型来渲染部分

@{Html.RenderPartial("SearchList", Model);}

【讨论】:

  • 更改代码,它正在工作,但是当我单击过滤器按钮时会生成另一个文本框。为什么会这样..谢谢..
  • 试试return PartialView("SearchList", query.ToList());。你需要使用SearchList局部视图
猜你喜欢
  • 2019-08-21
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 2017-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多