Search code examples
c#asp.net-mvchtml-helper

Why I've got Exception of type 'System.StackOverflowException' was thrown. in my own htmlhelper?


I've written htmlhelper for checkbox in asp.net mvc but when I want to use it.It shows me a exception.System.StackOverflowException' was thrownHow to solve it.and I also how to submit checkbox value to htmlhelper in fact,I want to submit value checkbox to my htmlhelper.

 public static class HelperUI
    {
        public static MvcHtmlString CheckBoxSimple(this HtmlHelper htmlHelper, bool IsCheck, string name, object htmlAttributes)
        {
            string checkBoxWithHidden = htmlHelper.CheckBoxSimple(IsCheck, name, htmlAttributes).ToHtmlString();
            string pureCheckBox = checkBoxWithHidden.Substring(0, checkBoxWithHidden.IndexOf("<input", 1));
            return new MvcHtmlString(pureCheckBox);
        }
    }




<div class="col-md-6">
    <div class="form-group row">
        status
        <div class="col-md-9">
            @Html.CheckBoxSimple(true, "Status", new { @class = "form-control", placeholder = "status" })

        </div>
    </div>
</div>

Solution

  • StackOverflowExceptions are often caused by an infinite loop or infinite recursion.

    In your case CheckBoxSimple is calling itself indefinitely : the first line calls CheckBoxSimple instead of CheckBox.