gpt4 book ai didi

c# - 如何在 Razor View 中将@model 指令更改为不同的模型?

转载 作者:太空狗 更新时间:2023-10-29 20:31:22 25 4
gpt4 key购买 nike

我有一个 Controller ,它创建一个模型并调用一个将模型作为参数传递的 View 。在 View 中有一个@model 指令指定模型的类型。我想重用相同的 View ,但从 Controller 传递不同的模型。是否可以动态(或有条件地)更改 View 中的@model 指令?

例如,在我的 Controller 操作中:

var contactsModel = db.GetContacts();
var companiesModel = db.GetCompanies();
return (someCondition)? View(contactsModel):View(companiesModel);

那么如何在 View 指令中定义 @model 来满足这两个模型呢?我希望相同的 View 根据传递的模型类型呈现信息。

谢谢。


更新:

谢谢,但我只需要对不同的模型使用一个通用 View 。

这是可能的,这是如何做到的。

在我定义的 View 中:

@model IEnumerable<MvcApplication1.Models.IBaseInterface>

在我定义的模型类中:

public interface IBaseInterface { }

public class Contact: IBaseInterface {}

public class Company: IBaseInterface {}

然后,在我使用的 View 中:

@if (Model is List<Contact>) {
@foreach (var item in (List<Contact>)Model)
{ // Here item has type Contact }
}

@if (Model is List<Company>) {
@foreach (var item in (List<Company>)Model)
{ // Here item has type Company }
}

完美运行:)

最佳答案

Is it possible to dynamically (or conditionally) change @model directive in the View?

没有。

如果您需要传递不同的模型,这意味着您需要不同的 View :

return (someCondition) 
? View("Contacts", contactsModel)
: View("Companies", companiesModel);\

ASP.NET MVC 中的基本规则如下:每个 View 一个 View 模型

关于c# - 如何在 Razor View 中将@model 指令更改为不同的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11487707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com