如何有条件地设置在asp.net MVC视图模型? [英] How to conditionally set a model in asp.net MVC view?

查看:199
本文介绍了如何有条件地设置在asp.net MVC视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET MVC。结果$ B $初学者b我的页面有一个叫_Navigation,我重用。结果
局部视图如果用户是在家的< A> 的导航需要指向的#字符,如果用户是在服务页面,导航的href需要指向其他网址,让我们说www.mysite.com。它会在这个菜单太等环节发生。

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.

我试着做以下

@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?

推荐答案

您可以尝试使用接口

public interface INavigation
{
    //Your props here
}

public class ServicesNavigation : INavigation
{
}

public class HomeNavigation: INavigation
{
}

然后您的视图的类型可以是INavigation的。

Then your view can be of type INavigation.

@model INavigation

而在根据你的情况你的控制器,你可以通过 INavigation 的impementation你想要的。

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

这篇关于如何有条件地设置在asp.net MVC视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆