How to conditionally set a model in asp.net MVC view?

我是研究僧i 提交于 2019-12-05 17:41:21

You can try using Interface.

public interface INavigation
{
    //Your props here
}

public class ServicesNavigation : INavigation
{
}

public class HomeNavigation: INavigation
{
}

Then your view can be of type INavigation.

@model INavigation

And in your controller based on your conditions you can pass the impementation of INavigation you want.

.......
INavigation model;
if(conditionOneIsMet)
{
    model = new ServicesNavigation();    
}
else
{
    model = new HomeNavigation();
}

return View(model);

Your view is in fact a class derived from the WebViewPage<TModel> class. The @model statement defines type of the model (TModel) Because it is the compile time statement, you can't change it in run time.

If you need two different models, you should have two different views.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!