将webform转换为mvc所需的Scriptmanager等效

时间:2014-09-25 10:21:42

标签: c# asp.net asp.net-mvc webforms

基本上我有一个带有scriptmanager和一个按钮的webform,用于更新从类webspider返回的结果(web spider搜索给定url的断开链接)。我正在尝试将代码转换为mvc并且已经实现了大部分内容,除了用粗体突出显示的代码,因为我在mvc视图中没有scriptmanager,有些人可以给我一些关于如何做到这一点的指示,非常感谢。 -

default.aspx -

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="_check404._Default" %>

<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
    <section class="featured">
        <div class="content-wrapper">
            <hgroup class="title">
                <h1><%: Title %>.</h1>
                <h2>Modify this template to jump-start your ASP.NET application.</h2>
            </hgroup>
            <p>
                To learn more about ASP.NET, visit <a href="http://asp.net" title="ASP.NET Website">http://asp.net</a>.
                The page features <mark>videos, tutorials, and samples</mark> to help you get the most from ASP.NET.
                If you have any questions about ASP.NET visit
                <a href="http://forums.asp.net/18.aspx" title="ASP.NET Forum">our forums</a>.
            </p>
        </div>
    </section>
</asp:Content>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
    <h3>Search results:</h3>

    <asp:Label ID="lblTot" runat="server"  />

<asp:Label runat="server" ID="lblStatus" />
 <asp:UpdatePanel runat="server" ID="pnlLinks"> 
    <ContentTemplate> --> 
        <asp:GridView runat="server" ID="grvLinks" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="NavigateUrl" HeaderText="Url" />
                <asp:ButtonField DataTextField="Status" HeaderText="Status" />
            </Columns>
        </asp:GridView>
        <asp:Button runat="server" ID="btnUpdateResults" Text="Update Results" />
 </ContentTemplate>
</asp:UpdatePanel>

default.aspx.cs -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using _check404.Spider;
using System.Net;

namespace _check404
{
     public partial class _Default : Page
    {

        private string script = @"setTimeout(""__doPostBack('{0}','')"", 5000);";
        private WebSpider WebSpider
        {
            get { return (WebSpider)(Session["webSpider"] ?? (Session["webSpider"] = new WebSpider())); }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.WebSpider.IsRunning)
            {
                string url = "http://bbc.co.uk";
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                    this.WebSpider.Execute(url);
                lblTot.Text = WebSpider.Tot.ToString();
            }

//////////////////////////以下代码是我要转换的内容

         if (this.WebSpider.IsRunning)
           {
               this.lblStatus.Text = "Processing...";
               ScriptManager.RegisterStartupScript(this, this.GetType(),
                   this.GetType().Name, string.Format(script, this.btnUpdateResults.ClientID), true);
           }

/////////////////////////////////////////////// ////////////////////////////////////////

            this.grvLinks.DataSource = this.WebSpider.Links;
            this.grvLinks.DataBind();
        }


    }
}

spider.cs -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;

namespace _check404.Spider
{
    public class WebSpider
    {
        public int Tot { get; set; }
        const int LIMIT = 10;
        string[] invalidTypes = { ".zip", ".doc", ".css", ".pdf", ".xls", ".txt", ".js", ".ico" };
        public List<Link> Links;
        public bool IsRunning { get; set; }
        public WebSpider()
        {
            this.Links = new List<Link>();
        }
        public void Execute(string url)
        {
            this.Links.Clear();
            this.Links.Add(new Link() { Status = HttpStatusCode.OK, NavigateUrl = url });
            this.IsRunning = true;
            WaitCallback item = delegate(object state) { this.FindLinks((UrlState)state); };
            ThreadPool.QueueUserWorkItem(item, new UrlState() { Url = url, Level = 0 });
            Tot = Links.Count();
        }
        public void FindLinks(UrlState state)
        {
            try
            {
                string html = new WebClient().DownloadString(state.Url);
                MatchCollection matches = Regex.Matches(html, "href[ ]*=[ ]*['|\"][^\"'\r\n]*['|\"]");
                foreach (Match match in matches)
                {
                    string value = match.Value;
                    value = Regex.Replace(value, "(href[ ]*=[ ]*')|(href[ ]*=[ ]*\")", string.Empty);
                    if (value.EndsWith("\"") || value.EndsWith("'"))
                        value = value.Remove(value.Length - 1, 1);
                    if (!Regex.Match(value, @"\((.*)\)").Success)
                    {
                        if (!value.Contains("http:"))
                        {
                            Uri baseUri = new Uri(state.Url);
                            Uri absoluteUri = new Uri(baseUri, value);
                            value = absoluteUri.ToString();
                        }
                        if (this.Links.Exists(x => x.NavigateUrl.Equals(value))) continue;
                        try
                        {
                            bool validLink = true;
                            foreach (string invalidType in invalidTypes)
                            {
                                string v = value.ToLower();
                                if (v.EndsWith(invalidType) || v.Contains(string.Format("{0}?", invalidType)))
                                {
                                    validLink = false;
                                    break;
                                }
                            }
                            if (validLink)
                            {
                                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(value);
                                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                                this.Links.Add(new Link() { Status = response.StatusCode, NavigateUrl = value });
                                if (response.StatusCode == HttpStatusCode.OK && state.Level < LIMIT)
                                {
                                    WaitCallback item = delegate(object s) { FindLinks((UrlState)s); };
                                    ThreadPool.QueueUserWorkItem(
                                        item, new UrlState() { Url = value, Level = state.Level + 1 });
                                }
                            }
                        }
                        catch
                        {
                            this.Links.Add(new Link()
                            {
                                Status = HttpStatusCode.ExpectationFailed,
                                NavigateUrl = value
                            });
                        }
                    }

                }
            }
            catch
            {
                ///
                /// If downloading times out, just ignore...
                /// 
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果蜘蛛作业正在运行,您似乎试图在5秒后自动单击按钮。

所有脚本管理器正在做的是在生成标记时嵌入包含javascript的标记。

我想说最简单的方法是在模型中添加一个属性。

class MyModel
{
    public bool SpiderRunning { get; set; }
} 

然后在你的控制器中设置它:

model.SpiderRunning = this.WebSpider.IsRunning

然后在您的视图中,如果此值为true,则仅将脚本添加到页面中:

@if(Model.SpiderRunning)
{
    <script>setTimeout(function(){document.getElementById("btnUpdateResults").click();}, 5000);</script>
}