Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3: Add usercontrol to Razor view

I have a DLL that contain a user control inside, in the Web Form view i can easily use it by using

<%@ Register Assembly = "..." Namespace = "..." TagPrefix = "..." %>

But how to do it in Razor view?

like image 374
Hieu Nguyen Trung Avatar asked Jun 11 '11 17:06

Hieu Nguyen Trung


2 Answers

You can't add server side controls to Razor views. In general it is very bad practice to do so anyways in an ASP.NET MVC application. Due to the heritage of WebForms view engine you could violate this rule but in Razor things have been made clearer.

This being said you could still do some pornography in Razor and include a WebForms partial which will contain the user control (totally not recommended, don't even know why I am mentioning it but anyway):

@Html.Partial("_Foo")

where in _Foo.ascx you could include server side controls:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%@ Register Assembly="SomeAssembly" Namespace="SomeNs" TagName="foo" %>

<foo:SomeControl runat="server" ID="fooControl" />
like image 171
Darin Dimitrov Avatar answered Dec 10 '22 23:12

Darin Dimitrov


Also, not recommended, but you can render a control in code, like in an HTML Helper:

public static string GenerateHtmlFromYourControl(this HtmlHelper helper, string id)
{
    var yourControl = new YourControl();

    yourControl.ID = id;

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

    yourControl.RenderControl(htmlWriter);

    return htmlWriter.InnerWriter.ToString();
}

and then you can reference it from your view:

Html.GenerateHtmlFromYourControl("YourControlId")

Just make sure you set up/reference your namespaces correctly to do this.

Caveat

FYI, I'm pretty sure there are some severe limitations regarding the Page Lifecycle here...

like image 34
John B Avatar answered Dec 10 '22 22:12

John B