在局部视图内调用ASP.NET Core视图组件

问题描述 投票:1回答:2

我有一个局部视图(_FormCustomer),显示用于创建客户的表单。我还具有一个视图组件(Countrylist),该组件生成国家/地区的选项列表。现在,我想在表格中显示国家列表。这就是我的工作:

Index.cshtml

<partial name="_FormCustomer" for="@Model._Customer" />

_FormCustomer.cshtml

<select asp-for="@Model.Land" class="form-control">
    @await Component.InvokeAsync("Countrylist");
</select>

CountrylistViewComponent.cs

public async Task<IViewComponentResult> InvokeAsync()
{
    return View(await _countryRepository.GetCountriesAsync());
}

((函数GetCountriesAsync()返回国家列表;可以正常工作。)

Pages/Componenst/Countrylist/default.cshtml

@model List<Country>
@foreach (Country country in Model)
{
    <option value="@country.code">@country.name</option>
}

[不幸的是,当我叫局部声时,select-box保持为空。但是,当我直接从@await Component.InvokeAsync("Countrylist");调用Index.cshtml时,它可以正常工作。

因此,您似乎无法在部分视图内使用视图组件。这个结论对吗?还是我做错了?

asp.net-core razor .net-core partial-views asp.net-core-viewcomponent
2个回答
1
投票

感谢Phantom2018,在您发帖后发现了问题。

@ 0:我正在使用Razor页面

@ 1:无效

@ 2:这是我的问题,而不是我的代码中的错字

@ 3:调试器向我显示vie组件被调用,所以

我的实际代码有点不同,如果可以的话,我想预先选择一个国家:

<select asp-for="@Model.Country" class="form-control">
    @if (Model == null)
    {
        await Component.InvokeAsync("Countrylist");
    }
    else
    {
        await Component.InvokeAsync("Countrylist", Model.Country);
    }  
</select>

经过一些测试,我找到了解决方案:

<select asp-for="@Model.Country" class="form-control">
    @if (Model == null)
    {
        @await Component.InvokeAsync("Countrylist");
    }
    else
    {
        @await Component.InvokeAsync("Countrylist", Model.Country);
    }  
</select>

不知道为什么,但是我不得不在等待之前使用@


0
投票

我现在已经测试了这种情况,并且可以将数据直接加载到页面中或将其包含在部分视图中时,可以确认数据加载正常。 (我已经在Razor页面上对此进行了测试-但是在使用MVC时它可能会起作用。如果您使用的是MVC或Razor页面,则没有提及。)

几件事,您可以尝试查看加载是否正常:

1)从所有“选择”和“部分”中删除“ for *”属性。这样,您可以先检查数据是否加载,然后再担心绑定到所选项目。 (此外,在提供的代码中,您省略了模型变量-因此无法对其进行注释。)

2)删除最后一个“;”在您的_FormCustomer.cshtml

<select asp-for="@Model.Land" class="form-control">
    @await Component.InvokeAsync("Countrylist")
</select>

请注意,我删除了结尾的“;”在等待语句中。我注意到“;”在选择中被添加为另一个“选项”!

3)我还注意到,即使是很小的语法错误(Intellisense不会识别)也会导致选择无法加载。调试以查看是否真正调用了您的InvokeAsync-在发生较小语法错误的情况下,甚至没有调用InvokeAsync。

还请记住:

“当partial view is instantiated收到时,父级的ViewData字典。对内部数据的更新部分视图不会保留到父视图。 ViewData的变化返回部分视图时,部分视图将丢失。“

© www.soinside.com 2019 - 2024. All rights reserved.