利用MvcHtmlString在后台生成HTML




    要引用System.Web.Mvc;

    模式:


public static MvcHtmlString FunctionName(this HtmlHelper html,[参数1],。。。)
{
    //    要组装的Html
    return new MvcHtmlString(组装的Html);
}
    this HtmlHelper html 这个参数很重要


    调用的时候 this HtmlHelper html 这个参数可以忽略

    @Html.FunctionName([参数1],。。。)


    Html控件的返回值

    每一个Html控件都返回了MvcHtmlString ,他继承了HtmlString,微软把他定义为不能再次编辑的Html字符串。如MvcHtmlString : HtmlString。知道了返回值我们就知道从哪里入手写自己的控件了。

    自定义Html控件

    先看个例子 我们用html写这样一段代码


<label for='male'>男</label>
<input type="radio" name="sex" id="male"/>
<br />
<label for='female'>女</label>
<input type="radio" name="sex" id="female"/>
其运行效果为:



public static MvcHtmlString Sex()
{
   string htmlStr = "<label for='male'>男</label>";
    Str += "<input type=\"radio\" name=\"sex\" id=\"male\"/>";
    Str += "<br />";
    Str +="<label for='female'>女</label>";
    Str += "<input type=\"radio\" name=\"sex\" id=\"female\"/>"
   return new MvcHtmlString(Str );
}

    页面调用

    @Html.Sex();

    其运行效果为:



打赏

取消 我去学网

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少
微信

打开微信扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

  1. #2

    木庄网络博客(2016/10/28 11:41:03)
    不错的网站主题,看着相当舒服

  2. #1

    木庄网络博客(2016/10/14 21:02:39)
    博客做得好漂亮哦!