创建HTML Helper方法-MVC框架 [英] Creating Html Helper Method - MVC Framework

查看:79
本文介绍了创建HTML Helper方法-MVC框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从MSDN网站上的Stephen Walther教程中学习MVC.他建议我们可以创建Html Helper方法.

I am learning MVC from Stephen Walther tutorials on MSDN website. He suggests that we can create Html Helper method.

说例子

using System;
namespace MvcApplication1.Helpers
{
          public class LabelHelper
          {
               public static string Label(string target, string text)
               {
                    return String.Format("<label for='{0}'>{1}</label>",
                    target, text);
               }
          }
}

我的问题需要在哪个文件夹下创建这些课程?

My Question under which folder do i need to create these class?

查看文件夹还是控制器文件夹?还是可以将其放在App_Code文件夹中?

View folder or controller folder? or can i place it in App_Code folder?

推荐答案

我将创建一个子文件夹Extensions,其中定义了辅助方法:

I would create a subfolder Extensions in which define helper methods:

namespace SomeNamespace
{
    public static class HtmlHelperExtensions
    {
        public static string MyLabel(this HtmlHelper htmlHelper, string target, string text)
        {
            var builder = new TagBuilder("label");
            builder.Attributes.Add("for", target);
            builder.SetInnerText(text);
            return builder.ToString();
        }
    }
}

在您看来,您需要引用名称空间并使用扩展方法:

In your view you need to reference the namespace and use the extension method:

<%@ Import Namespace="SomeNamespace" %>

<%= Html.MyLabel("abc", "some text") %>

这篇关于创建HTML Helper方法-MVC框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆