I am trying to implement auto closing custom helper.
I have found how to to this below:
Custom html helpers: Create helper with "using" statement support
I have done everything except:
what i am supossed to return here?
public static Action BeginField(this HtmlHelper htmlHelper, string formName)
{
string result = string.Format("<div class=\"FullWidthForm\"><span>{0}</span>", formName);
result += "<ul class=\"Left\">";
htmlHelper.ViewContext.HttpContext.Response.Write(result);
return ???????
}
I am asking because i have error as follows:
Error 9 ‘FieldContainer.BeginField(System.Web.Mvc.HtmlHelper,
string)’: not all code paths return a
value
so i do not have idea what to return
Ok I have created everything how ever:
public static class DisposableExtensions
{
public static IDisposable DisposableField(this HtmlHelper htmlHelper, string formName)
{
//'HtmlHelpers.DisposableHelper' does not contain a constructor that takes 2 arguments
return new DisposableHelper(
() => htmlHelper.BeginField(formName),
() => htmlHelper.EndField());
}
public static void BeginField(this HtmlHelper htmlHelper, string formName)
{
htmlHelper.ViewContext.HttpContext.Response.Write("<ul><li>" + formName + "</li>");
}
public static void EndField(this HtmlHelper htmlHelper)
{
htmlHelper.ViewContext.HttpContext.Response.Write("</ul>");
}
}
class DisposableHelper : IDisposable
{
private Action end;
// When the object is create, write "begin" function
// make this public so it can be accessible
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();
}
}
Your
BeginFielddoes not need to returnAction.Action is a delegate, a callback you need to pass to the
DisposableHelperconstructor. You will setup it as() -> htmlHelper.BeginField(formName). DisposableHelper works by remembering the two callbacks you pass in – first to start the tag (BeginField) which is called immediately, second to end the tag (EndField) which is called on disposal of theDisposableHelper.UPDATE: This is how you should implement it.
a) Copy the
DisposableHelperclass.b) Write an extension to
DisposableExtensions:c) Change your
BeginFielddeclaration to returnvoid:d) Add
EndFieldmethod to close the tag.e) Use it this way: