ASP.NET MVC Helpers,为模型的两个属性创建帮助器

时间:2014-12-20 09:29:53

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我需要为模型的两个属性创建帮助器 例如

@Html.TestFor(m => m.Item1, m=>m.Item2)

那么如何为这个助手编写方法呢?

例如

public static MvcHtmlString TestFor<TModel, TValue>
          (this HtmlHelper<TModel> self,
          Expression<Func<TModel, TValue>> expression)
        {
...
}

仅为模型的一个属性的方法。 如何写几个属性? 感谢您的想法

2 个答案:

答案 0 :(得分:2)

您可以在助手中使用多个表达式:

public static MvcHtmlString TestFor<TModel, TValue>
          (this HtmlHelper<TModel> self,
          Expression<Func<TModel, TValue>> expression, Expression<Func<TModel, TValue>> secondExpression)
{
...
}

或使用params表示多个表达式并在以后使用表达式数组:

public static MvcHtmlString TestFor<TModel, TValue>
          (this HtmlHelper<TModel> self,
          params Expression<Func<TModel, TValue>>[] expressions)
{
...
}

答案 1 :(得分:2)

如果属性类型彼此不同,则使用如下:

public static MvcHtmlString ImageFor<TModel, TProperty, KProperty>(
            this HtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TProperty>> expressionImageProperty,//this is HttpPostedFile
            Expression<Func<TModel, KProperty>> expressionImageIdProperty,//this property is ID for image that store in database
            object filehtmlAttributes, object imageBoxHtmlAttributes)//html attributes for html controls
        {
            var sb = new StringBuilder();
            var fileattr = new RouteValueDictionary(filehtmlAttributes);
            if (!fileattr.ContainsKey("id"))
                fileattr.Add("id", string.Format("ImageForFile_{0}", ((MemberExpression)expressionImageProperty.Body).Member.Name));
            fileattr.Add("type", "file");
            if (!fileattr.ContainsKey("class"))
                fileattr.Add("class", "form-control");
            fileattr.Add("onchange", "readURL(this);");
            sb.Append((string)htmlHelper.TextBoxFor<TModel, TProperty>(expressionImageProperty, fileattr).ToHtmlString());

            TagBuilder tagImg = new TagBuilder("img");
            tagImg.Attributes.Add("id", string.Format("ImageForFileViewer_{0}", ((MemberExpression)expressionImageProperty.Body).Member.Name));

            if (htmlHelper.ViewData.Model == null)
                tagImg.Attributes.Add("src",
                    new UrlHelper(HttpContext.Current.Request.RequestContext).Action("GetImage", "ImageManagement",
                        new { imageId = "0" }));
            else
            {
                var modelImageId = expressionImageIdProperty.Compile()(htmlHelper.ViewData.Model).ToString();
                if (string.IsNullOrEmpty(modelImageId))
                    modelImageId = "0";
                tagImg.Attributes.Add("src",
                    new UrlHelper(HttpContext.Current.Request.RequestContext).Action("GetImage", "ImageManagement", //ImageManagementController get FileResult
                        new
                        {
                            imageId = modelImageId,thumb=true,size="small"
                        }));
            }

            if (imageBoxHtmlAttributes != null)//
                tagImg.MergeAttributes(new RouteValueDictionary(imageBoxHtmlAttributes));//

            sb.Append(tagImg.ToString(TagRenderMode.Normal));

            sb.Append((string)htmlHelper.HiddenFor<TModel, KProperty>(expressionImageIdProperty).ToHtmlString()); //for update

            sb.AppendLine(
               EngineContext.Current.Resolve<IPageScriptManager>()//this is simple mvc script manager resolved from IOC
                                 .ScriptInclude<CommonResourceAccessor>("imageFor" + "_script",
                                                                        "***.WebFramework.Resources.ImageFor.js")//if you have some js file add as resource
                                 .Render().ToString());
            return MvcHtmlString.Create(sb.ToString());
        }