【问题标题】:Updating Data in Table from AJAX Call从 AJAX 调用更新表中的数据
【发布时间】:2013-12-17 16:08:16
【问题描述】:

编辑:好的,所以我通过将return 语句更改为return PartialView("_GridView", model); 来调用部分视图_GridView,但它不会用我的数据更新表。我已经对其进行了跟踪,它正在发送正确的模型并使用正确的数据遍历表,并且 AJAX 调用成功,但数据仍然是相同的数据。有什么想法吗?

我在一个视图中有两个局部视图。一个有几个我用作过滤器的下拉列表,另一个是显示数据库信息的表:

我的观点:

@model IEnumerable<PPL.Models.GridPart>

@{
    ViewBag.Title = "Index";


}



<h2>Index</h2>




<div id="dropDownsDiv">
    @Html.Partial("_DropDownsView", Model)
</div>


<div id="theGrid">
    @Html.Partial("_GridView", Model)
</div>

局部视图_GridView:

@model IEnumerable<PPL.Models.GridPart>

@{
    ViewBag.Title = "_GridView";
}
<div id="theGrid">
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Category)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Type)
        </th>
        <th>
            @*@Html.DisplayNameFor(model => model.PartNum)*@
            Part #
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Status)
        </th>        
        <th>
            @Html.DisplayNameFor(model => model.REL)
        </th>


    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Category)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Type)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.PartNum)
            </td>
            <td bgcolor="#@Html.DisplayFor(modelItem => item.StatusColor)">
                @Html.DisplayFor(modelItem => item.Status)
            </td>
            <td bgcolor="#@Html.DisplayFor(modelItem => item.RELColor)">
                @Html.DisplayFor(modelItem => item.REL)
            </td>


        </tr>

    }


</table>

局部视图_DropDownsView:

@{
    ViewBag.Title = "_DropDownsView";


}

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>


<script type="text/javascript">
    // assuming you're using jQuery

    $(document).ready(function () {
        $("#Categories").change(function () {

            //alert("I'm here!");

            //Update typeDropDown
            $.ajax({
                url: '/Part/Myajaxcall',
                type: 'POST',
                datatype: 'json',
                data: { id: $("#Categories").val() },
                success: function (data) {
                    $('#typeDropDown option[value!="0"]').remove()                    
                    $.each(data, function (i, item) {
                        $('#typeDropDown').append('<option value="' + item.DescriptorID + '">' + item.pplType + '</option>');                                                
                    });                   
                },
                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });



            //Update Data Grid
            $.ajax({
                url: '/Part/updateGrid',
                type: 'POST',
                datatype: 'json',
                data: { id: $("#Categories").val() },
                success: function (data) {
                    alert("Got it!");
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });




        });
    });



</script>


Category:  @Html.DropDownList("Categories", "          ") 

Type: <select id="typeDropDown"><option value="0"></option></select>

Manufacturer: @Html.DropDownList("Manufacturers", "          ") 

我想要完成的是,当从“类别”下拉列表中选择一个项目时,我想首先通过 AJAX 更新第二个下拉列表(它正在工作),接下来,我想用我的数据。

这是我的控制器:

public class PartController : Controller
    {
        private PartContext db = new PartContext();


        //
        // GET: /Part/

        public ActionResult Index()
        {


            //Use LINQ to query DB & Get all of the parts
            //Join PPLPart & PPLDescriptor Tables
            var myParts = from p in db.Parts
                          join d in db.Descriptors on p.DescriptorID equals d.DescriptorID
                          select new
                          {
                              Category = d.DescriptorDesc,
                              TypeCol = p.PPLType,
                              PartNumber = p.PartNum,
                              Status = p.PPLStatus,
                              StatusColor = p.PPLStatusBGColor,
                              REL = p.RELStatus,
                              RELColor = p.RELStatusBGColor
                          };

            //Drop the parts into a List            
            List<GridPart> pl = new List<GridPart>();

            foreach (var m in myParts)
            {
                GridPart gp = new GridPart();
                gp.Category = m.Category;
                gp.Type = m.TypeCol;
                gp.PartNum = m.PartNumber;
                gp.Status = m.Status;
                gp.StatusColor = m.StatusColor;
                gp.REL = m.REL;
                gp.RELColor = m.RELColor;

                pl.Add(gp);
            }

            var model = pl;


            //Pass info for Categories drop-down
            ViewBag.Categories = new SelectList(db.Descriptors, "DescriptorID", "DescriptorDesc");

            //Pass info for Manufacturer drop-down
            ViewBag.Manufacturers = new SelectList(db.Manufacturers, "ManufacturerID", "ManufacturerName");




            //Pass off to View
            return View(model);
        }


        [HttpPost]
        public ActionResult updateGrid(string id)
        {
            int intID = Convert.ToInt32(id);

            //Use LINQ to query DB & Get all of the parts
            //Join PPLPart & PPLDescriptor Tables
            var myParts = from p in db.Parts
                          join d in db.Descriptors on p.DescriptorID equals d.DescriptorID
                          where d.DescriptorID == intID
                          select new
                          {
                              Category = d.DescriptorDesc,
                              TypeCol = p.PPLType,
                              PartNumber = p.PartNum,
                              Status = p.PPLStatus,
                              StatusColor = p.PPLStatusBGColor,
                              REL = p.RELStatus,
                              RELColor = p.RELStatusBGColor
                          };

            //Drop the parts into a List            
            List<GridPart> pl = new List<GridPart>();

            foreach (var m in myParts)
            {
                GridPart gp = new GridPart();
                gp.Category = m.Category;
                gp.Type = m.TypeCol;
                gp.PartNum = m.PartNumber;
                gp.Status = m.Status;
                gp.StatusColor = m.StatusColor;
                gp.REL = m.REL;
                gp.RELColor = m.RELColor;

                pl.Add(gp);
            }

            var model = pl;



            return PartialView(model);
        }


        [HttpPost]
        public JsonResult Myajaxcall(string id)
        {

            int intID = Convert.ToInt32(id);

            var types = from c in db.Types
                             where c.DescriptorID == intID
                             select new { did = c.DescriptorID, pType = c.pplType };

            List<PPLType> typesList = new List<PPLType>();

            foreach (var t in types)
            {
                PPLType p = new PPLType();
                p.DescriptorID = t.did;
                p.pplType = t.pType;

                typesList.Add(p);
            }



            //string command = "EXEC dbo.pr_PPLDescriptor_list";
            //List<int> results = db.Database.SqlQuery(int, command, null);


            return Json(typesList, JsonRequestBehavior.AllowGet);
        }

    }

任何帮助将不胜感激。

【问题讨论】:

  • 您是按类别和类型过滤网格,还是仅按类别过滤?
  • 现在,只是类别
  • 我很确定我的问题是返回 PartialView(model);在控制器的 updateGrid 中。它不会将模型传递给局部视图。
  • 在此处查看接受的解决方案:stackoverflow.com/questions/14750946/…

标签: ajax asp.net-mvc


【解决方案1】:

好的,我明白了。因此,如上所述,为了通过 AJAX 将新模型传递给局部视图,我将操作结果的返回值更新为:

return PartialView("_GridView", model);

需要返回一个局部视图,并传入您要传递给的局部视图的名称作为第一个参数,以及您要传递的模型作为第二个参数。

然后,为了在局部视图中刷新数据表中的数据,我将其添加到我的 AJAX 中:

$('#theGrid').html(数据);

基本上,这就是更新包含表格的 div 的内容。

感谢大家的所有 cmets。希望这对其他人有帮助。

【讨论】:

  • 您好,您的解决方案是正确的。几件事情要提到你可以改进你的解决方案。由于您只获取表和下拉列表的数据,而不更改数据库中的任何内容,因此您可以执行获取请求。
【解决方案2】:

您的解决方案是正确的。

几件事情要提到你可以改进你的解决方案。由于您只获取表格和下拉列表的数据,而不更改数据库中的任何内容,因此您可以执行获取请求。

看起来您的 Index 操作和 UpdateGrid 使用相同的代码,因此您可以使用单个操作并返回不同的结果。

在您的索引操作中,您可以使用Request.IsAjaxRequest() 检查通过ajax 发出请求的天气。

    [HttpGet]
    public ActionResult Index(string id)
    {
        //create a predicate and default it to true
        Expression<Func<Descriptor, bool>> predicate = d => true;

        if(Request.IsAjaxRequest())
        {
            //when an ajax request is made, convert the id to int
            int intID = Convert.ToInt32(id);
            //overwrite the predicate with your condition and use it in the where clause
            predicate = d => d.DescriptorID == intID
        }

        //Use LINQ to query DB & Get all of the parts
        //Join PPLPart & PPLDescriptor Tables
        var myParts = from p in db.Parts
                      join d in db.Descriptors on p.DescriptorID equals d.DescriptorID
                      where predicate
                      select new
                      {
                          Category = d.DescriptorDesc,
                          TypeCol = p.PPLType,
                          PartNumber = p.PartNum,
                          Status = p.PPLStatus,
                          StatusColor = p.PPLStatusBGColor,
                          REL = p.RELStatus,
                          RELColor = p.RELStatusBGColor
                      };

        //Drop the parts into a List            
        List<GridPart> pl = new List<GridPart>();

        foreach (var m in myParts)
        {
            GridPart gp = new GridPart();
            gp.Category = m.Category;
            gp.Type = m.TypeCol;
            gp.PartNum = m.PartNumber;
            gp.Status = m.Status;
            gp.StatusColor = m.StatusColor;
            gp.REL = m.REL;
            gp.RELColor = m.RELColor;

            pl.Add(gp);
        }

        var model = pl;

        if(Request.IsAjaxRequest())
        {
            return PartialView(model);
        }
        else
        {
            //Pass info for Categories drop-down
            ViewBag.Categories = new SelectList(db.Descriptors, "DescriptorID", "DescriptorDesc");

            //Pass info for Manufacturer drop-down
            ViewBag.Manufacturers = new SelectList(db.Manufacturers, "ManufacturerID", "ManufacturerName");

            //Pass off to View
            return View(model);
        }
    }

现在您的 ajax 调用必须更改如下

//Update Data Grid
        $.ajax({
            url: '/Part/Index',
            type: 'GET',
            datatype: 'json',
            data: { id: $("#Categories").val() },
            success: function (data) {
                $('#theGrid').html(data);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 2012-02-06
    • 2023-04-09
    • 2019-03-20
    • 2015-05-06
    相关资源
    最近更新 更多