Using ASP.NET Server Controls in MVC?

£可爱£侵袭症+ 提交于 2019-12-19 11:45:32

问题


On my current project I need to add a functionality that allows the user to view a thumbnail of their uploaded PDF. I've found a handy component that achieves this (the basic version is free, but it's enough for my current needs). Anyways, the control is pretty outdated (2010), therefore there doesn't seem to be MVC support. On the demos they depict usage of the control as such:

The View's Markup:

<form method="post" runat="server" enctype="multipart/form-data">
       <asp:Panel ID="thumbnailsPanel" runat="server" />
</form>

The thumbnail control is instantiated via code, the byte array which represents the thumbnail is passed to the control and the control is added to thumbnailsPanel

<script runat="server">
protected void DisplayThumbs_Click( object sender, System.EventArgs e )
{
      Thumbnail thumbnail = new Thumbnail();
      thumbnail.SessionKey = sessionID;
      thumbnail.Index = i;
      thumbnailsPanel.Controls.Add( thumbnail );
}
</script>

Given that I can't declare a Thumbnail control in my razor view, how would I used this control in MVC? I've spent a few hours trying to make this control MVC friendly to no avail, the best I've come up with is to include a .ASPX view (not.cshtml) in my project and render the Thumbnail control on that view. Obviously this is not desirable.

So how would you go about using a ASPX server controls in MVC? Is the idea a bad one altogether and should not be practised?


回答1:


I worked around it in a project of mine by reimplementing the control as a HtmlHelper. Assuming the control isn't too complicated then it should work for you too. Do this:

  1. Dump the Control's source using Reflector
  2. Massage the source so it actually compiles (as source from Reflector doesn't usually compile straight away)
  3. Identify what state the control has. Convert the state from member properties into members of its own new ViewModel class.
  4. Find the Render method and convert it to a HtmlHelper that uses ViewContext.Writer

For example:

public class FooControl : Control {
    public String Message { get; set; }

    public override void Render(HtmlTextWriter wtr) {
        wtr.WriteLine("<p>");
        wtr.WriteLine( message );
        wtr.WriteLine("</p>");
    }
}

Becomes this:

public class FooViewModel {
    public String Message { get; set; }
}

// This method should exist in a static Extensions class for HtmlHelper
public static void Foo(this HtmlHelper html, FooViewModel model) {
    HtmlTextWriter wtr = html.ViewContext.Writer;
    wtr.WriteLine("<p>");
    wtr.WriteLine( model.Message );
    wtr.WriteLine("</p>");
}


来源:https://stackoverflow.com/questions/13405955/using-asp-net-server-controls-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!