Произошло необработанное исключение при обработке запроса на _Partial Page - PullRequest
0 голосов
/ 13 марта 2019

Вид верхнего уровня страницы называется «Create.cshtml»

На этой странице мне нужно разместить несколько _partialViews.cshtml, которые я сделал, используя страницы бритвы:

<div>
    <row>
         <div class="col-md-6">
            @await Html.PartialAsync("~/Views/Shared/_PartialDelegates")
         </div>
         <div class="col-md-6">
            @await Html.PartialAsync("~/Views/Shared/_PartialApps")
        </div>
    </row>
</div>

Теперь проблема в том, что я пытаюсь вызвать _PartialDelegates.cshtml w / _PartialDelegates.cs

_PartialDelegates.cshtml

@page
@model IMP.ECR.WEB.Views.Shared._PartialDelegatesModel
@{
}
<partial name="_PartialDelegatesView" model="Model.Avengers" />

Который вызывает _PartialDelegates.cshtml.cs

using Microsoft.AspNetCore.Mvc.RazorPages;

namespace IMP.ECR.WEB.Views.Shared
{
    public class _PartialDelegatesModel : PageModel
    {
    public List<string> Avengers = new List<string>();      


    public void OnGet()
    {
        Avengers.AddRange(new[] { "Spiderman", "Iron Man", "Dr. Stange", "The Hulk" });
    }
    }
  }
}

Тогда в _PartialDelegatesView.cshtml у меня есть следующее:

@model List<string>
<div class="col-md-12">
    <h2>Avengers</h2>
    <table class="table table-boardered table-striped" style="width:100%">
        @foreach (var item in Model)
        {
            <tr>
                <td>@item</td>
            </tr>
        }
    </table>
</div>

Но я получаю необработанное исключение ---

 An unhandled exception occurred while processing the request.
 NullReferenceException: Object reference not set to an instance of an 
 object.
 AspNetCore.Views_Shared__PartialDelegates.get_Model()

NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Shared__PartialDelegates.get_Model()
AspNetCore.Views_Shared__PartialDelegates.ExecuteAsync() in _PartialDelegates.cshtml
+
<partial name="_PartialDelegatesView" model="Model.Avengers" />
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper.RenderPartialCoreAsync(string partialViewName, object model, ViewDataDictionary viewData, TextWriter writer)
Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper.PartialAsync(string partialViewName, object model, ViewDataDictionary viewData)
AspNetCore.Views_Sponsors_Create.ExecuteAsync() in Create.cshtml
+
            @await Html.PartialAsync("~/Views/Shared/_PartialDelegates.cshtml")
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync<TFilter, TFilterAsync>()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Ответы [ 2 ]

1 голос
/ 14 марта 2019

Загрузка страниц бритвы как частичное представление кажется невозможной, см. здесь . Страницы бритвы нельзя использовать в качестве замены для Просмотр компонентов . Выполните следующие шаги, чтобы создать PartialDelegates ViewComponent, который мог бы делать то же самое, что и вы.

1.Создайте папку ViewComponens и добавьте класс PartialDelegates.cs в папку

public class PartialDelegates:ViewComponent
{
    public IViewComponentResult Invoke()
    {
        List<string> Avengers = new List<string>();
        Avengers.AddRange(new[] { "Spiderman", "Iron Man", "Dr. Stange", "The Hulk" });
        return View(Avengers);
    }

}

2.Добавить Default.cshtml к пути /Views/Shared/Components/PartialDelegates/Default.cshtml (создать папку, если она не существует)

@model List<string>
<h1>Default</h1>
<partial name="_PartialDelegatesView" model="Model" />

3. В вашем Create.cshtml вызовите View Component

@await Component.InvokeAsync("PartialDelegates")
0 голосов
/ 14 марта 2019

Вам необходимо удалить директиву @page в _PartialDelegates.cshtml, чтобы частичный просмотр работал правильно.Но проблема в том, что метод _PartialDelegatesModel OnGet никогда не вызывается, и поэтому список Avengers не создается.

Кажется невозможным использовать страницу бритвы как это частичное представление, только обычное представление бритвы подходит для этой цели.Если вам нужно создать экземпляры некоторых значений перед рендерингом страницы, то в соответствии с docs (раздел "Важное")

Если вам нужно выполнить код, используйте представление компонент вместо частичного представления.

...