如何在MVC中基于按钮单击将linq结果显示到局部视图并刷新局部视图?

时间:2018-12-31 11:05:47

标签: asp.net-mvc updatepanel partial-views

我有一个页面,其左侧包含作业列表,右侧包含一个局部视图,以显示所选作业的详细信息(局部视图仅在用户单击某个作业时显示),但我无法通过选择了工作ID,但没有在我的局部视图中看到它。

 public ActionResult Index(int? id)
        {

            var selectedjob = db.Postings.ToList();
            if (Request.IsAjaxRequest())
            {
                 selectedjob = db.Postings.Where(p => p.PostingId == id).ToList();
                ViewBag.sss = selectedjob;
                return PartialView("_JobDetails", selectedjob);
            }

            return View("Index", selectedjob);
            //return View(db.Postings.ToList());
        }

1 个答案:

答案 0 :(得分:0)

要刷新局部视图(选定的作业详细信息),您需要进行ajax调用。

例如

让我们说以下是您的工作清单html。

    <ul>
       <li>
          <a hre="javascript:;" data-jobid="1" class="job-desc">Job 1 </a>              
       </li>
       <li>             
          <a hre="javascript:;" data-jobid="2" class="job-desc">Job 2 </a>
       </li>
    </ul>

让我们假设职位的jquery click事件为-

 $(document).on('click', '.job-desc', function () {
    var JobId = $(this).data('jobid'); // This will get the clicked job's Id

    $.ajax({
        url: "@Url.Action("Index","Home")",
        type: 'post',
        dataType:"HTML", // as we will be returning Partial view
        data: { id: JobId },
        success: function (data) {
            $('#job-details').html(data); // assuming that your job details is under "job-details" as div id
        }
    });
});

现在您在Home控制器中的操作结果将类似于-

    public ActionResult Index(int? id)
    {
        var selectedjob = db.Postings.ToList();
        if (Request.IsAjaxRequest())
        {
             selectedjob = db.Postings.Where(p => p.PostingId == id).ToList();
             ViewBag.sss = selectedjob;

        }
        return PartialView("_JobDetails", selectedjob);
    }