03-自定义HtmlHelper辅助方法

HtmlHelper是视图中的强大的帮助类。

在mvc中因为没有了webform的各种控件。但是MVC提供了各种HtmlHelper给我们使用。通过htmlhelper我们可以实现和创建各种东西。

htmlhelper除了可以帮我们渲染页面控件外。还可以定义一些辅助方法。我们这集先来讲解一些辅助方法。

如果要返回控件,则我们的htmlheper的方法要返回MvcHtmlString类型的值

如果是辅助方法,我们可以返回字符串或者整数等类型。

下面我们来试一下添加一个htmlhelper方法,目的是用来截取多少个字符串。末尾用…后缀。

辅助方法代码

namespace WebApplication1.Cores
{
    public static class MyHtmlHelper
    {
        public static string CutString(this HtmlHelper htmlHelper, string input, int length, string cur)
        {
            if (string.IsNullOrEmpty(input))
            {
                return string.Empty;
            }
            if (input.Length<=length)
            {
                return input;
            }

            return input.Substring(0, length) + cur;
        }
    }
}Code language: JavaScript (javascript)

视图调用示例

@using WebApplication1.Cores

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var title = "讲述MVC的基本使用。在进阶课程里面。我们可能涉及到很多底层的东西。希望同学们能够在这套课程中,学到更多的开发经验。和一些开发技巧。";
    
}

<h2>@ViewBag.Page</h2>
@Html.CutString(title,12,"...")Code language: PHP (php)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注