MVC页面使用扩展HtmlHelper案例1

1.新建一个UserHelper 和  tb_User 类

public static class UserHelper
    {
        public static string UserShow(this HtmlHelper<tb_User> helper)
        {
            var user = helper.ViewData.Model;
            if (user.UserName == "dzw")
            {
                return string.Format("<div>我是{0}</div>", user.UserName);
            }
            else
            {
                return "<div>找不到</div>";
            }

        }
    }

2.controller返回视图

        public ActionResult IndexTwo()
        {

            return View(new tb_User { UserName = "dzw"});
        }

3.页面引用UserHelper相同的命名空间

@model MvcModelApp.Models.tb_User
@using MvcModelApp.Helper
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>IndexTwo</title>
</head>
<body>
    <div> 
        @Html.Raw(Html.UserShow())
    </div>
</body>
</html>

运行显示结果如下:

 

 

posted @ 2019-01-14 22:36  蜗牛的礼物  阅读(169)  评论(0编辑  收藏  举报