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

扶醉桌前 提交于 2019-12-10 09:26:38

问题


I am a beginner in ASP.NET MVC.
My page has one partial view called _Navigation that I am reusing.
If the user is in the "Home" the <a> of the navigation needs to point to the "#" char, if the user is in the "Services" page, the href of the navigation needs to point to other url, let's say "www.mysite.com". It will occur with other links in this menu too.

I tried to do the following

@if (ViewContext.RouteData.Values.ContainsValue("Services"))
{
    @model MySite.Models.ServicesNavigation
}
else
{
    @model MySite.Models.HomeNavigation
}

But it says I can have only one model.
How to solve it?


回答1:


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);



回答2:


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.



来源:https://stackoverflow.com/questions/33977514/how-to-conditionally-set-a-model-in-asp-net-mvc-view

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