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?
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.
来源:https://stackoverflow.com/questions/33977514/how-to-conditionally-set-a-model-in-asp-net-mvc-view