カスタムHTMLヘルパー:文のサポート「を使用して」とヘルパーを作成します。

StackOverflow https://stackoverflow.com/questions/676746

  •  21-08-2019
  •  | 
  •  

質問

私は私の最初のasp.net MVCアプリケーションを書いていると私は、カスタムHTMLヘルパーについて質問があります:

フォームを作るために、あなたが使用することができます:

<% using (Html.BeginForm()) {%>
   *stuff here*
<% } %>

私は、カスタムHTMLヘルパーと似た何かをしたいと思います。 言い換えれば、私は変更したい:

Html.BeginTr();
Html.Td(day.Description);
Html.EndTr();

に:

using Html.BeginTr(){
    Html.Td(day.Description);
}

このことは可能ですか?

役に立ちましたか?

解決

ここでは、C#での可能な再利用可能な実装は、次のとおりです。

class DisposableHelper : IDisposable
{
    private Action end;

    // When the object is created, write "begin" function
    public DisposableHelper(Action begin, Action end)
    {
        this.end = end;
        begin();
    }

    // When the object is disposed (end of using block), write "end" function
    public void Dispose()
    {
        end();
    }
}

public static class DisposableExtensions
{
    public static IDisposable DisposableTr(this HtmlHelper htmlHelper)
    {
        return new DisposableHelper(
            () => htmlHelper.BeginTr(),
            () => htmlHelper.EndTr()
        );
    }
}

この場合、BeginTrEndTr直接応答ストリームに書き込みます。

:あなたは、文字列を返す拡張メソッドを使用する場合は、それらを使用して出力する必要があります
htmlHelper.ViewContext.HttpContext.Response.Write(s)

他のヒント

私はMVC3にここに与えられたアドバイス、次の試してみましたが、私は使用してトラブルに走っます:

htmlHelper.ViewContext.HttpContext.Response.Write(...);
私はこのコードを使用すると、私のレイアウトがレンダリングされる前に

、私のヘルパーは、応答ストリームに書いていました。これはうまく動作しませんでした。

その代わり、私はこれを使用しました

htmlHelper.ViewContext.Writer.Write(...);

あなたは(CodePlexにする rel="noreferrer">

static MvcForm FormHelper(this HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes)
{
    TagBuilder builder = new TagBuilder("form");
    builder.MergeAttributes<string, object>(htmlAttributes);
    builder.MergeAttribute("action", formAction);
    builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true);
    htmlHelper.ViewContext.HttpContext.Response.Write(builder.ToString(TagRenderMode.StartTag));

    return new MvcForm(htmlHelper.ViewContext.HttpContext.Response);
}

MvcFormクラスはIDisposableインターを実装し、それにDisposeメソッドは、レスポンスにを書き込んでいます。

だから、何をする必要があると思いますが、それはDisposeメソッドがオフのタグを閉じますで...あなたはヘルパーメソッドで実行したいタグを記述し、IDisposableをを実装するオブジェクトを返します。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top