简体   繁体   English

使用不同的控制器和模型的MVC共享部分视图

[英]MVC Shared Partial Views using different controllers and models

I have 2 controllers that generate 2 index views. 我有2个控制器,它们生成2个索引视图。 What i would like to do is use these views as global shared partial views but cant seem to get this working. 我想做的是将这些视图用作全局共享的部分视图,但似乎无法正常工作。

Does anyone know if this is even possible? 有谁知道这是否有可能?

My controller code is 我的控制器代码是

  public ActionResult Index()
        {

            var viewModel = (from P in db.Projects
                             join R in db.Reports on P.ProjectTitle equals R.ReportProjectID into ps
                             from R in ps.DefaultIfEmpty()
                             select new MyViewModel { Project = P, Report = R });


            return View(viewModel);
        }

My ViewModel code is 我的ViewModel代码是

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    namespace MiLife2.ViewModels
    {
    public class MyViewModel
    {
        public Project Project { get; set; }
        public Report Report { get; set; }
    }
    }

and my view is 我的看法是

    @model IQueryable<MiLife2.ViewModels.MyViewModel>

    @{
    ViewBag.Title = "Index";
    }
    enter code here

<h2>Index</h2>
<div>@Html.Partial("_Partial1")</div>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
    </tr>

@foreach (var item in Model)
{
    <tr>
        <td>@item.Project.ProjectTitle </td>
        <td>@item.Project.ProjectCreatedByID</td>
        <td>@item.Project.ProjectCreatedDate</td>


        <td>@if (item.Report == null)
            {
                <text>No Reports</text>
            }
            else
            {
               @item.Report.Title;
            }
        </td>
        <td>@if (item.Report == null)
            {
                <text> </text>
            }
            else
            {
               @item.Report.Description;
            }</td>

        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Project.ProjectID }) |
            @Html.ActionLink("Details", "Details", new {  id=item.Project.ProjectID }) |
            @Html.ActionLink("Delete", "Delete", new {  id=item.Project.ProjectID })
        </td>
    </tr>
}

</table>

If i create a partial page and paste the above view into it and then use @HTML.Partial("_ProjPartial") i get the error 如果我创建一个部分页面并将上面的视图粘贴到其中,然后使用@ HTML.Partial(“ _ ProjPartial”),则会收到错误消息

The model item passed into the dictionary is of type 'System.Collections.Generic.List 1[MiLife2.Project]', but this dictionary requires a model item of type 'System.Linq.IQueryable 1[MiLife2.ViewModels.MyViewModel]'. 传递到字典中的模型项的类型为“ System.Collections.Generic.List 1[MiLife2.Project]', but this dictionary requires a model item of type 'System.Linq.IQueryable 1 [MiLife2.ViewModels.MyViewModel]” 。

This does not happen if i use @HTML.Partial("_ProjPartial") from within the Index cshtml page in the specific controller views folder. 如果我在特定控制器视图文件夹的Ind​​ex cshtml页面中使用@ HTML.Partial(“ _ ProjPartial”),则不会发生这种情况。

From the error it looks like to me that your partial view is looking for the same model as you have on your view. 从错误看来,在我看来,您的局部视图正在寻找与视图相同的模型。 Passing the model to your partial should fix that error 将模型传递给您的局部模型应该可以解决该错误

@Html.Partial("_Partial1", Model)

update: 更新:

since that didn't work for you I would try using an ajax call 因为那对您不起作用,所以我尝试使用ajax调用

$('.btnSubmit').on('click', function(){
    $.ajax({
         url: "@(Url.Action("Action", "Controller"))",
         type: "POST",
         cache: false,
         async: true,
         data: { id: id },
         success: function (result) {
             $(".Content").html(result);
         }
    });

 });

then in your controller 然后在您的控制器中

public PartialViewResult GetPartial()
    {

        var viewModel = (from P in db.Projects
                         join R in db.Reports on P.ProjectTitle equals R.ReportProjectID into ps
                         from R in ps.DefaultIfEmpty()
                         select new MyViewModel { Project = P, Report = R });


        return PartialView("_Partial1", viewModel);
    }

Using this ajax call you can call the partial view from any view and you can pass different id's, on button clicks or as needed to refresh the view. 使用此ajax调用,您可以从任何视图调用局部视图,还可以传递不同的ID,单击按钮或根据需要刷新视图。 Hopefully calling it this way will fix your error. 希望以这种方式调用它可以解决您的错误。 let me know if you have any questions. 如果您有任何问题,请告诉我。

Recently ran into something similar, so I wanted to add my 2 cents. 最近遇到了类似的情况,因此我想加2美分。 The answer for me was in what I was passing to the Partial View. 对我来说,答案是我传递给部分视图。

I was attempting to pass a string to a partial view, but when that string happened to be null , it was acting as if I had not passed anything into the Partial, which means it defaulted to passing the the current view's model. 我试图将字符串传递给部分视图,但是当该字符串碰巧为null ,它的作用就好像我没有将任何内容传递给Partial一样,这意味着它默认情况下会传递当前视图的模型。

For example, I have a view which renders a partial and that partial takes in a string: 例如,我有一个渲染部分视图的视图,该部分采用了字符串:

@model SomeModel

@{ Html.RenderPartial("_MyPartialView", SomeModel.StringProperty) }

If SomeModel.StringProperty happens to be null , then it is going to try and pass what ever the current view's model is (which, in this case is SomeModel ). 如果SomeModel.StringProperty恰好为null ,则它将尝试传递当前视图的模型(在本例中为SomeModel )。 So instead, I simply wrote the following which will pass in an empty string if SomeModel.StringProperty happens to be null: 因此,我只是编写了以下代码,如果SomeModel.StringProperty恰好为null,则将传递空字符串:

@model SomeModel

@{ Html.RenderPartial("_MyPartialView", SomeModel.StringProperty ?? string.Empty) }

Hope this helps someone. 希望这对某人有帮助。

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

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