How to conditionally set a model in asp.net MVC vi

2019-05-10 11:49发布

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?

2条回答
聊天终结者
2楼-- · 2019-05-10 12:00

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);
查看更多
男人必须洒脱
3楼-- · 2019-05-10 12:02

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.

查看更多
登录 后发表回答