How can I use the HTML helper in the extension method?

I have the following classes:

public class Note { public string Text { get; set; } public RowInfo RowInfo { get; set; } } public class RowInfo { [DisplayName("Created")] public DateTime Created { get; set; } [DisplayName("Modified")] public DateTime Modified { get; set; } } 

In my opinion, I have the following that creates HTML with the correct name and value:

 Html.HiddenFor(model => model.Note.Created) 

Now what I'm trying to do is create an extension method that will include the above and which I can call in each view. I tried to do the following. I think I'm on the right track, but I don't know how to make the equivalent of " model => model.Note.Created ". Can someone give me some tips on how I can do this and that I will need to replace the text inside the parenthesis, I don’t have a model, but I can do it differently so that the hidden field looks at my class, to get the correct DisplayName the same as above?

  namespace ST.WebUx.Helpers.Html { using System.Web.Mvc; using System.Web.Mvc.Html using System.Linq; public static class StatusExtensions { public static MvcHtmlString StatusBox(this HtmlHelper helper, RowInfo RowInfo ) { return new MvcHtmlString( "Some things here ... " + System.Web.Mvc.Html.InputExtensions.Hidden( for created field ) + System.Web.Mvc.Html.InputExtensions.Hidden( for modified field ) ); } } 
+4
source share
1 answer

You can write a strongly typed helper with a Ξ»-expression:

 public static class StatusExtensions { public static IHtmlString StatusBox<TModel, TProperty>( this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> ex ) { return new HtmlString( "Some things here ... " + helper.HiddenFor(ex)); } } 

and then:

 @Html.StatusBox(model => model.RowInfo.Created) 

UPDATE:

As requested in the comments section here is a revised version of the helper:

 public static class StatusExtensions { public static IHtmlString StatusBox<TModel>( this HtmlHelper<TModel> helper, Expression<Func<TModel, RowInfo>> ex ) { var createdEx = Expression.Lambda<Func<TModel, DateTime>>( Expression.Property(ex.Body, "Created"), ex.Parameters ); var modifiedEx = Expression.Lambda<Func<TModel, DateTime>>( Expression.Property(ex.Body, "Modified"), ex.Parameters ); return new HtmlString( "Some things here ..." + helper.HiddenFor(createdEx) + helper.HiddenFor(modifiedEx) ); } } 

and then:

 @Html.StatusBox(model => model.RowInfo) 

Needless to say, custom HTML helpers should be used to create small parts of HTML. Complexity can grow quickly, in which case I would recommend that you use an editor template for the RowInfo type.

+4
source

Source: https://habr.com/ru/post/1381950/


All Articles