简体   繁体   English

通过ajax渲染部分视图

[英]render partial view through ajax

I have a dashboard view. 我有一个仪表板视图。 In this dashboard I want to render number of partial views. 在此仪表板中,我要渲染一些局部视图。 I started this exercise just for learning purpose. 我开始此练习只是为了学习。 Actually I am not sure what I am doing wrong. 其实我不确定自己在做什么错。 Here is my code: 这是我的代码:

My DashboardController: 我的DashboardController:

public ActionResult DashboardIndex()
        {
            return View();
        }

        public ActionResult DebitAndCreditExpensesPV()
        {
            DashboardModel objGet = new DashboardModel();
            DashboardViewModel objVM = new DashboardViewModel();
            DateTime date = new DateTime();
            objVM.StartDate = new DateTime(date.Year, date.Month, 1);
            objVM.EndDate = objVM.StartDate.AddMonths(1).AddDays(-1);
            objVM.ExpenseType = objGet.GetExpensesByDebitAndCredit(objVM.StartDate, objVM.EndDate);
            return PartialView(objVM);
        }

My DashboardIndex.cshtml 我的DashboardIndex.cshtml

@model GPI.ViewModel.DashboardViewModel
@{
    ViewBag.Title = "DashboardIndex";
}


<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="col-md-4">
                   @{
                       Html.RenderPartial("DebitAndCreditExpensesPV");
               }
            </div>
            <div class="col-md-8"></div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {

        $.ajax({

            type: "get",
            url: "/Dashboard/DebitAndCreditExpensesPV",
            data: {
                'startDate': $('#StartDate').val(),
                'endDate': $('#EndDate').val()
            },
            dataType: 'json',
            success: function () {
                alert('success');
            },
            error: function () {
                alert('failure');
            }
        });
    });
</script>

DashboardModel.cs DashboardModel.cs

public class DashboardViewModel
    {
        public double ExpenseAmount { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public ExpenseList ExpenseType { get; set; } 
    }

    public class ExpenseList 
    {
        public double TotalDebits { get; set; }
        public double TotalCredits { get; set; }
    }

My Partial View: DebitAndCreditExpensesPV.cshtml 我的部分视图:DebitAndCreditExpensesPV.cshtml

@model GPI.ViewModel.DashboardViewModel
<div class="row">
    <div class="col-sm-4 col-md-12">
        <div class="stat-panel">
            <div class="stat-row">
                <div class="stat-cell bg-pa-purple padding-sm">
                    <div class="col-xs-6">
                        <div class="text-xs" style="margin-bottom:5px;">
                            Debit EXPENSES
                        </div>
                        <div style="width:100%;display:inline-block;margin-bottom:-2px;position:relative;">
                            <span class="text-xlg">
                                <span class="text-lg text-slim">&#8377;</span>
                                <strong>@Model.ExpenseType.TotalDebits</strong>
                            </span>
                        </div>
                    </div>
                    <div class="col-xs-6">
                        <div class="text-xs" style="margin-bottom:5px;">
                            Credit EXPENSES
                        </div>
                        <div style="width:100%;display:inline-block;margin-bottom:-2px;position:relative;">
                            <span class="text-xlg">
                                <span class="text-lg text-slim">&#8377;</span>
                                <strong>@Model.ExpenseType.TotalCredits</strong>
                            </span>
                        </div>
                    </div>

                </div>
            </div>
            <div class="stat-row">
                <div class="stat-counters bordered no-border-t text-center">
                    <div class="stat-cell col-xs-12 padding-sm">
                        <div class="input-daterange input-group" id="datepicker">
                            @Html.TextBoxFor(m => m.StartDate,"{0:d}", new { @class = "input-sm form-control" })
                            <span class="input-group-addon">to</span>
                            @Html.TextBoxFor(m => m.EndDate, "{0:d}", new { @class = "input-sm form-control" })
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

I put two break points in my controller: one at 'DashboardIndex' action and other at 'DebitAndCreditExpensesPV'. 我在控制器中放置了两个断点:一个在“ DashboardIndex”操作上,另一个在“ DebitAndCreditExpensesPV”上。 The first one executes but later one does not. 第一个执行,但后一个不执行。 After first breakpoint, I got 'object null reference ' exception in my partial view at this line <strong>@Model.ExpenseType.TotalDebits</strong> . 在第一个断点之后,我在部分视图的此行<strong>@Model.ExpenseType.TotalDebits</strong>获得了“对象空引用”异常。

I want to know why second breakpoint is not executing. 我想知道为什么第二个断点没有执行。 I this break point executes, I can not get this exception. 如果执行此断点,则无法获取此异常。 Please tell me where I am going wrong. 请告诉我我要去哪里了。

In the RenderPartial method, you are calling the DebitAndCreditExpensesPv partial view. RenderPartial方法中,您正在调用DebitAndCreditExpensesPv局部视图。 This view is strongly typed to your DashboardViewModel and you are using different properties of this Model inside the view (Ex : Model.ExpenseType.TotalDebits ). 此视图已强类型Model.ExpenseType.TotalDebits DashboardViewModel并且您正在视图中使用此Model的不同属性(例如: Model.ExpenseType.TotalDebits )。

But in your Index view, you are not passing any model object to your RenderPartial method. 但是在索引视图中,您没有将任何模型对象传递给RenderPartial方法。 If you do not pass any object in this method, It will try to use the Model of the parent view(Index). 如果您没有在此方法中传递任何对象,它将尝试使用父视图的模型(索引)。 In your case, You Index view does not have any model, So the essentially the Model which the partial view now has is NULL . 在你的情况,你索引视图没有任何模式,所以基本上它的局部视图现在有型号为NULL。 You are trying to access the ExpenseType property of NULL and that is the reason you are getting the exception. 您正在尝试访问NULL的ExpenseType属性,这就是您获取异常的原因。

Even if you fix your index view to pass the model, You are doing it twice. 即使您修复了索引视图以通过模型,也要进行两次。 Once via RenderPartial and again you are making a call to the DebitAndCreditExpensesPV method via ajax on the document ready event. 一次通过RenderPartial然后再次通过ajax在document ready事件上调用DebitAndCreditExpensesPV方法。 May be you can get rid of the RenderPartial call. 也许您可以摆脱RenderPartial调用。

So in your index view, Add a div to show the result of the ajax call. 因此,在索引视图中,添加一个div以显示ajax调用的结果。

<div id="divDebitAndCredit"></div>

And your script to load the markup to this div. 然后将脚本加载到此div的脚本。 I removed the datatype:"json" as we do not want receive the data in json format. 我删除了datatype:"json"因为我们不想接收json格式的数据。

$(function () {

    $.ajax({
        type: "get",
        url: "@Url.Action("DebitAndCreditExpensesPV","Home")",
        data: {
            'startDate': $('#StartDate').val(),
            'endDate': $('#EndDate').val()
        },           
        success: function (r) {
            $("#divDebitAndCredit").html(r);
        },
        error: function (a,b,c) {
            alert('Error ! See browser console');
            console.log(b,c);
        }
    });

});

Now in the above code, you are trying to send the startDate and endDate to the action method. 现在,在上面的代码中,您尝试将startDate和endDate发送到action方法。 So update your action method to accept those. 因此,请更新您的操作方法以接受这些操作。

public ActionResult DebitAndCreditExpensesPV(DateTime? startDate,DateTime? endDate)
{          
    DashboardViewModel objVM = new DashboardViewModel();
    DateTime date = DateTime.Now; 
    if(startDate!=null)
    {
        objVM.StartDate = startDate.Value;
    }
    else
    {
        objVM.StartDate = new DateTime(date.Year, date.Month, 1);
    }
    if(endDate!=null)
    {
        objVM.EndDate = endDate.Value;
    }
    else
    {
        objVM.EndDate = objVM.StartDate.AddMonths(1).AddDays(-1);
    }       
        objVM.ExpenseType = new ExpenseList { TotalCredits = 45.00, TotalDebits = 634.00 };
    return PartialView(objVM);
}

But the startDate and endDate input fields are part of the partial view. 但是startDateendDate输入字段是部分视图的一部分。 so when you make the ajax call in the ready event of the index view, those fields won't be part of your page. 因此,当您在索引视图的ready事件中进行ajax调用时,这些字段将不属于您的页面。 You can either keep the Partial view inside our div and pass a DashboardViewModel object to the Partial view 您可以将Partial视图保留在div中,然后将DashboardViewModel对象传递给Partial视图

@model DashboardViewModel
<div id="divDebitAndCredit">
    @{ Html.RenderPartial("DebitAndCreditExpensesPV",Model) }
</div>

This means your Index action should send an object of DashboardViewModel to the index view with whatever default values you want to render. 这意味着您的Index操作应将DashboardViewModel对象与您要呈现的任何默认值一起发送到索引视图。

public ActionResult Index()
{
    var objVM = new DashboardViewModel();
    DateTime date = DateTime.Now;
    objVM.StartDate = new DateTime(date.Year, date.Month, 1);
    objVM.EndDate = objVM.StartDate.AddMonths(1).AddDays(-1);
    objVM.ExpenseType = new ExpenseList { TotalCredits = 45.00, TotalDebits = 634.00 };

    return View(objVM);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM