[英]ASP.NET MVC 4 pass model from view to html helper
I want to pass my ViewModel(not IEnumerable) to my custom html helper 我想将我的ViewModel(不是IEnumerable)传递给我的自定义html助手
I was doing on IEnumerable like this: 我在IEnumerable上这样做:
Helper: 帮手:
public static IHtmlString GenerateTable<TModel, TValue>(this HtmlHelper<TModel> inHtml, IEnumerable<TValue> model)
View: 视图:
@Html.GenerateTable(Model)
But how i can pass model which is not IEnumerable to helper? 但是我怎么能把不是IEnumerable的模型传递给帮手呢?
I Tried this: 我试过这个:
public static MvcHtmlString MyHelper<TModel>(this HtmlHelper<TModel> html, object obj)
{}
but when i call it like this 但当我这样称呼它
@Html.MyHelper(Model)
obj is always NULL
obj总是
NULL
Try like this: 试试这样:
public static MvcHtmlString MyHelper<TModel>(this HtmlHelper<TModel> htmlHelper)
{
TModel model = htmlHelper.ViewData.Model;
// TODO: do something with the model ...
}
and in your strongly typed view: 并在您的强类型视图中:
@model MyViewModel
@Html.MyHelper()
我已经尝试过你的代码并且它工作正常,如果模型已经初始化......所以我认为你应该检查@nemesv的建议但是我会澄清,当你调用视图时应该检查传递模型......你需要检查模型并确保它不为空
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.