Is it possible to create a custom ASP.NET MVC strongly typed HTML Helper?

大城市里の小女人 提交于 2019-11-29 03:21:02

Ok, I figured it out (and it was pretty straightforward...). Posting one of my overloads in case anyone else runs into this question.

public static string DatePickerFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel, TProperty>> expression)
  where TModel : class
{
    var inputName = ExpressionHelper.GetExpressionText(expression);
    return htmlHelper.DatePicker(inputName);
}

I just tried out the following to create a strongly typed CKEditor helper and it seems to be working flawlessly. This assumes that you already have included jquery and the necessary ckeditor scripts in your project. It might be nice to look at also setting the ckeditor config too, but this satisfied my current needs.

    public static MvcHtmlString CkEditor(this HtmlHelper htmlHelper, string name, string value, object htmlAttributes)
    {
        var output = htmlHelper.TextArea(name, value, htmlAttributes).ToString();
        output += string.Format("<script type=\"text/javascript\">$(document).ready(function(){{ $('#{0}').ckeditor(); }});</script>", name);

        return MvcHtmlString.Create(output);
    }

    public static MvcHtmlString CkEditor(this HtmlHelper htmlHelper, string name, string value)
    {
        return htmlHelper.CkEditor(name, value, null);
    }

    public static MvcHtmlString CkEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) where TModel : class
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        return htmlHelper.CkEditor(metadata.PropertyName, metadata.Model as string, htmlAttributes);
    }

    public static MvcHtmlString CkEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) where TModel : class
    {
        return htmlHelper.CkEditorFor(expression, null);
    }
public static string DatePickerFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel, TProperty>> expression)
  where TModel : class
{
    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    return htmlHelper.DatePicker(metadata.PropertyName);
}

I used ModelMetadata this will also work if you create a datetime template for datepicker.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!