How to include a partial view inside a webform

后端 未结 7 2220
灰色年华
灰色年华 2020-11-28 01:07

Some site I\'m programming is using both ASP.NET MVC and WebForms.

I have a partial view and I want to include this inside a webform. The partial view has some code

相关标签:
7条回答
  • 2020-11-28 02:08

    This solution takes a different approach. It defines a System.Web.UI.UserControl which can be place on any Web Form and be configured to display the content from any URL…including an MVC partial view. This approach is similar to an AJAX call for HTML in that parameters (if any) are given via the URL query string.

    First, define a user control in 2 files:

    /controls/PartialViewControl.ascx file

    <%@ Control Language="C#" 
    AutoEventWireup="true" 
    CodeFile="PartialViewControl.ascx.cs" 
    Inherits="PartialViewControl" %>
    

    /controls/PartialViewControl.ascx.cs:

    public partial class PartialViewControl : System.Web.UI.UserControl {
        [Browsable(true),
        Category("Configutation"),
        Description("Specifies an absolute or relative path to the content to display.")]
        public string contentUrl { get; set; }
    
        protected override void Render(HtmlTextWriter writer) {
            string requestPath = (contentUrl.StartsWith("http") ? contentUrl : "http://" + Request.Url.DnsSafeHost + Page.ResolveUrl(contentUrl));
            WebRequest request = WebRequest.Create(requestPath);
            WebResponse response = request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            var responseStreamReader = new StreamReader(responseStream);
            var buffer = new char[32768];
            int read;
            while ((read = responseStreamReader.Read(buffer, 0, buffer.Length)) > 0) {
                writer.Write(buffer, 0, read);
            }
        }
    }
    

    Then add the user control to your web form page:

    <%@ Page Language="C#" %>
    <%@ Register Src="~/controls/PartialViewControl.ascx" TagPrefix="mcs" TagName="PartialViewControl" %>
    <h1>My MVC Partial View</h1>
    <p>Below is the content from by MVC partial view (or any other URL).</p>
    <mcs:PartialViewControl runat="server" contentUrl="/MyMVCView/"  />
    
    0 讨论(0)
提交回复
热议问题