ASP.NET MVC Helpers, Merging two object htmlAttributes together

后端 未结 4 613
感情败类
感情败类 2021-02-01 03:46

I have a situation where I need to write an HTML Helper to extend another html helper. Normally, the helper would look like this.

@Html.TextAreaFo

4条回答
  •  难免孤独
    2021-02-01 04:02

    When I've to do that, I usually create a partial view Then I use RenderPartial:

    @Html.Partial(MVC.Shared.MyPartialView_cshtml, new ViewDataDictionary() {  
           { "Content", model.Content},
           { "Css", "some_other_css"},
    });
    

    I usually also create a Model class to avoid using magic string ( and ViewDataDictionary) like in the sample above. In your view you can

    • use the Content: @ViewBag.Content
    • test and use the default css if a custom one is not specified (@ViewBag.Css)

    A small note: it's also possible to change the default template used when calling TextAreaFor (or other similar method). For this, have a look at http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html

提交回复
热议问题