Search code examples
c#asp.net-mvc-4ascx

Control not rendering in MVC view


Before getting flack about using ascx controls in MVC let me preface that this is not what I would like to do! However the powers above me would like to continue to use the ascx control.

I started by using the following in my controller:

public ActionResult _CreditReporting(int id)
{
    return PartialView();
}

public static class myClass
{
    public static string GenerateHtmlFromYourControl(this HtmlHelper helper, string contId)
    {
        var credControl = new _person_creditreporting_control();

        credControl.ID = contId;

        var htmlWriter = new HtmlTextWriter(new StringWriter());

        credControl.RenderControl(htmlWriter);

        return htmlWriter.InnerWriter.ToString();
    }
}

and the following in my view

@using ds_iDMS.Controllers
    <div>
    @{
    Html.GenerateHtmlFromYourControl("_person_creditreporting_control.ascx");
    }
    </div>

Everything seems to be working properly and all the parameters are being passed etc. The ascx page is not rendering however and I am not sure why


Solution

  • I would change the view to

    @using ds_iDMS.Controllers
    <div>
        @Html.Raw(Html.GenerateHtmlFromYourControl("_person_creditreporting_control.ascx"))
    </div>
    

    Phil Haack has a good quick reference guide to different bits of the razor syntax. it might be a little outdated by now, but it is still a very useful overview.