使用Ajax将数据从Controller传递到View以过滤结果

时间:2013-09-16 15:50:30

标签: asp.net-mvc jquery razor

我正在尝试根据下拉选择的值过滤我的结果。所有的过滤和一切都在工作,我只是努力让我的观点更新结果。我遗漏了一些括号和其他不相关的代码。这就是我所拥有的:

public ViewResult Index()
{    
     -- this effectively returns all Invoices no matter what date --
     var data = new UserBAL().GetInvoice(date);
     return View(data);                 
}

我的Jquery和Ajax是:

 $(document).ready(function () {
     $("[name='DDLItems']").change(function () {
         var selection = $("[name='DDLItems']").val();
         var dataToSend = {
             //variable to hold selection?
             idDate: selection
         };

         $.ajax({
             type: "POST",
             url: "Invoice/FilterInvoice",
             data: dataToSend,
             success: function (data) {   
                $("#Index").html(data);                     
             }
[HttpPost]                     // Selected DDL value 
public ActionResult FilterInvoice(int idDate)
{       
     switch (idDate)
    { 
        case 0:
             date = DateTime.Parse("01-01-1754");
             break;

        case 3:
             date = DateTime.Now.AddMonths(-12);
             break;
     }
     //var data is returning my expected results 
     var data = new UserBAL().GetInvoice(date);

    // I know this isn't right and needs to be changed 
     return View(data);

我的ajax成功功能也没有做任何事情因此,我猜这需要一些调整。这也是我使用表格标签显示表格的方法。请记住,我留下了一些代码,但重要的是在这里,唯一的问题是将我的过滤结果渲染回视图,

  @foreach (var item in Model) {
  <tr><td>   
    @Html.DisplayFor(modelItem => item.Invoice_Number)        
    @Html.DisplayFor(modelItem => item.Amt_Total)
</td>

2 个答案:

答案 0 :(得分:1)

您可以将部分视图作为字符串返回,然后使用jquery在ajax成功中返回,而不是传递视图,您可以更新结果:

控制器逻辑:

[HttpPost]
public JsonResult FilterInvoice(int idDate)
{     
 .....  
 return Json((RenderRazorViewToString("YourViewName", data)), JsonRequestBehavior.AllowGet);
}


    [NonAction]
    public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

Ajax电话:

    $.ajax({
    //........
    success: function (result) {
        $("#Index").replaceWith(result);
    }
});

答案 1 :(得分:0)

如果其他人遇到这个问题,这就是答案。这就是我最终要做的事情,在我传递给函数URL的日期参数上传递过滤行。让网格填充在Ajax调用内部也似乎是一个问题,所以我不得不把它拿出来。

 public JsonResult JqGrid(int idDate)
    {
         switch (idDate)

         #region switch date
            --Switch Statement--
        #endregion
        var invoices = new UserBAL().GetInvoice(date);

        return Json(invoices, JsonRequestBehavior.AllowGet);
    }

    [HttpPost]  // pretty much does nothing, used as a middle man for ajax call 
    public JsonResult JqGridz(int idDate)
    {
        switch (idDate)
        #region switch date

          --Switch Statement--
        #endregion

        var invoices = new UserBAL().GetInvoice(date);

        return Json(invoices, JsonRequestBehavior.AllowGet);
    }

是的,这两个功能似乎非常多余,而且它们是。我不知道为什么我的帖子不会更新数据,但我每次都需要重新加载网格,当我这样做时它会调用第一个函数。所以jqGridz的帖子有点像个中间人。

这是我使用的jquery代码

var dropdown
var Url = '/Invoice/JqGrid/?idDate=0'  
         $(document).ready(function () {

$("#jqgrid").jqGrid({ 
    url: Url,
    datatype: 'json',
    mtype: 'GET', //insert data from the data object we created above 
    width: 500,  
    colNames: ['ID','Invoice #', 'Total Amount', 'Amount Due', 'Amount Paid', 'Due Date'], //define column names
    colModel: [
    { name: 'InvoiceID', index: 'Invoice_Number', key: true, hidden: true, width: 50, align: 'left' },
    { name: 'Invoice_Number', index: 'Invoice_Number', width: 50,  align: 'left'},
    { name: 'Amt_Total', index: 'Amt_Total', width: 50, align: 'left' },
    { name: 'Amt_Due', index: 'Amt_Due', width: 50, align: 'left' },
    { name: 'Amt_Paid', index: 'Amt_Paid', width: 50, align: 'left' },
    { name: 'Due_Date', index: 'Due_Date', formatter: "date", formatoptions: { "srcformat": "Y-m-d", newformat: "m/d/Y" }, width: 50, align: 'left' },

    ],                     
    pager: jQuery('#pager'), 
    sortname: 'Invoice_Number',  
    viewrecords: false, 
    editable: true,
    sortorder: "asc",  
    caption: "Invoices",       
});
$("[name='DDLItems']").change(function () {
    var selection = $(this).val();
     dropdown = {
        //holds selected value 
        idDate: selection
    };

    $.ajax({

        type: "POST",
        url: "Invoice/JqGridz",
        data: dropdown,
        async: false,
        cache: false,
        success: function (data) {         
            $("#jqgrid").setGridParam({ url: Url + selection})               
             $("#jqgrid").trigger('reloadGrid');
        }
    })      

  })
});