C# 在HtmlHelper中获取与相应视图关联的模型

C# 在HtmlHelper中获取与相应视图关联的模型,c#,asp.net,asp.net-mvc,html-helper,asp.net-mvc-3,C#,Asp.net,Asp.net Mvc,Html Helper,Asp.net Mvc 3,我的视图继承模型。我的模型 <%@ Page Language="C#" MasterPageFile="Something.Master" Inherits="Models.MyModel>" %> 有没有办法访问这个?可能通过ViewContext或ViewDataDictionary 我不想为我调用的每个助手显式传递Model.SessionKey。有没有我错过的方法?或者这是不可能的 谢谢。我的方法是让您希望与此助手一起使用的所有模型实现一个定义其公共属性的接口。Ht

我的视图继承模型。我的模型

<%@ Page Language="C#" MasterPageFile="Something.Master" Inherits="Models.MyModel>" %>
有没有办法访问这个?可能通过
ViewContext
ViewDataDictionary

我不想为我调用的每个助手显式传递
Model.SessionKey
。有没有我错过的方法?或者这是不可能的


谢谢。

我的方法是让您希望与此助手一起使用的所有模型实现一个定义其公共属性的接口。HtmlHelper对象上的ViewData属性具有模型属性(类型为
对象
)。在助手中,可以将其转换为接口类型。假设在该点上它是非空的,即实际上不是空的并且类型正确,那么您可以使用公共属性

public static string CustomerHelper( this HtmlHelper helper, ... )
{
    var model = helper.ViewData.Model as ISessionModel;

    var sessionKey = model.SessionKey;

    ...
}

类似地,您可以这样做:

public static string CustomerHelper( this HtmlHelper helper, ... )
{
    ISessionModel model = helper.ViewData.Model;

    var sessionKey = model.SessionKey;

    ...
}

唯一的区别是,您不必执行强制转换…

当然这不会编译,您是在隐式地将
对象
强制转换为
ISessionModel
public static string CustomerHelper( this HtmlHelper helper, ... )
{
    ISessionModel model = helper.ViewData.Model;

    var sessionKey = model.SessionKey;

    ...
}