简体   繁体   English

传递ViewModel两次查看

[英]Pass ViewModel to view twice

I have the following index-method in my homecontroller: 我的家庭控制器中有以下索引方法:

    var homeIndexModel = new HomeIndexModel()
    {
        ActiveTasks = tasks.Where(
            task =>
                task.TaskStatus != TaskStatusEnum.Deferred &&
                task.TaskStatus != TaskStatusEnum.Verified && task.TaskStatus != TaskStatusEnum.Resolved),
        ClosedTasks = tasks.Where(
                task =>                            
                    task.TaskStatus == TaskStatusEnum.Resolved),
        DeferredTasks = tasks.Where(
            task =>
                task.TaskStatus == TaskStatusEnum.Verified ||
                task.TaskStatus == TaskStatusEnum.Deferred),
        Rules = m_errandSvc.GetAllRules(),
        Sources =
            Enum.GetValues(typeof(TaskSourceEnum)).Cast<TaskSourceEnum>().AsEnumerable().OrderBy(taskSource => taskSource.AsString()),
        Types = 
            Enum.GetValues(typeof(TaskTypeEnum)).Cast<TaskTypeEnum>().AsEnumerable().OrderBy(taskSource => taskSource.AsString()),
        Counties = counties,
        Reports = null,
    };

    return this.View(homeIndexModel);

This homeIndexModel Is passed to the view when you visit the firstpage. 当您访问首页时,此homeIndexModel传递给视图。 As you can see, I assaign a Report-object to null. 如您所见,我将Report对象确定为null。

I want to use thise Report-property of homeIndexModel when I do a search On the firstpage. 我在首页上搜索时要使用homeIndexModel的Reporte属性。 When I hit "Search", a modal should appear and the search result printed out. 当我点击“搜索”时,应该出现一个模态并打印出搜索结果。

Here Is my search-method in the controller: 这是我在控制器中的搜索方法:

  [HttpPost]
        public ActionResult SearchReport(string searchVal, string searchParam)
        {
            var reports = m_errandSvc.GetReportSearch(searchVal, searchParam).ToList();
            var homeIndexModel = new HomeIndexModel()
            {
                Reports = reports
            };
            return this.View(homeIndexModel);
        } 

As you can see, I assaign the Report-property with the result of GetReportSearch. 如您所见,我使用GetReportSearch的结果来确定Report属性。 I want to loop through this object below: 我想在下面遍历此对象:

<!-- Modal -->
<div class="modal" id="myModalSearch" aria-hidden="true" data-keyboard="false" data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4>FISH</h4>
                        @if (Model.Reports != null)
                        {

                        }
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

The problem I have is that when I add a foreach, like this below, my debug-mode quits. 我的问题是,当我添加一个foreach时,如下所示,我的调试模式退出了。

   @if (Model.Reports != null)
   {
      foreach(var itm in Model.Reports)
      {
          <div>@itm.Report_id</div>
          <div>@itm.ReportSource</div>
      }
   }

How can I solve this whole thing with homeIndexViewModel and print out my search-result as I want to? 如何使用homeIndexViewModel解决整个问题,并根据需要打印出搜索结果?

Herer is my jQuery that I use to post to the search-method: Herer是我用来发布到搜索方法的jQuery:

    $('#searchReports').click(function () {

        var searchVal = $('#searchVal').val();

        $.ajax({
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "POST",
            url: DataReview.BASE + "/Home/SearchReport",
            data: JSON.stringify(
                {
                    'searchVal': searchVal,
                    'searchParam': searchParam
                }
            )
        }).done(function (data) {
            console.log("YES");
        }).fail(function(data) {
            console.log("Fail " + data);
        });
    });

Pass back the view model again on search and then assign the report to it this way. 在搜索时再次传递视图模型,然后以这种方式将报告分配给它。

 [HttpPost]
        public ActionResult SearchReport(string searchVal, string searchParam, HomeIndexModel homeIndexModel )
        {
            var reports = m_errandSvc.GetReportSearch(searchVal, searchParam).ToList();

            homeIndexModel.Reports = reports      

            return this.View(homeIndexModel);
        } 

Or the best practice is you can do a Ajax call and then get only the reports data and update your View page. 或最佳实践是您可以进行Ajax调用,然后仅获取报告数据并更新“视图”页面。 But this requires Jquery , let me know if you want help on implementing this. 但这需要Jquery ,如果您需要实施方面的帮助,请告诉我。

EDIT 1: Making small change to your code to get this job done by ajax. 编辑1:对您的代码进行少量更改以使该工作由Ajax完成。

    $.ajax({
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "POST",
            url: DataReview.BASE + "/Home/SearchReport",
            data: JSON.stringify(
                {
                    'searchVal': searchVal,
                    'searchParam': searchParam
                }
            )          
        })
        .done(function (reportData ) {              
            var $panelHeading = $('#myModalSearch .panel-heading');
            $('#myModalSearch .panel-heading').contents(':not(h4)').remove(); //remove previous search results
           $.each(reportData, function(i,v){             
                $panelHeading.append("<div>"+this.Report_id+"</div<div>"+this.ReportSource+"</div>");  //append new result
           });

        })

Your controller must return JSON rather than a view, So change the code to below one. 您的控制器必须返回JSON而不是视图,因此将代码更改为下面的代码。

[HttpPost]
    public ActionResult SearchReport(string searchVal, string searchParam)
    {
        var reports = m_errandSvc.GetReportSearch(searchVal, searchParam).ToList();

        return Content( new JavaScriptSerializer().Serialize(reports), "application/json");
    }

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

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