简体   繁体   English

动态添加控件可以使代码达到最佳状态

[英]How optimal the code can be with dynamically adding the controls

In a website I am designing I need to show images which I upload using asp:FileUpload control. 在我正在设计的网站中,我需要显示使用asp:FileUpload控件上传的图像。 So after uploading I am adding div, img and textarea using a string builder and then loading it into panel which I have already created. 因此,上传后,我将使用字符串生成器添加div,img和textarea,然后将其加载到我已经创建的面板中。 So is it better to use Stringbuilder to load inner HTML or is it good to use HtmlgenericControls to add the controls like image and textarea. 因此,最好使用Stringbuilder加载内部HTML,或者最好使用HtmlgenericControls添加诸如图像和文本区域之类的控件。 I am using C#. 我正在使用C#。 My current coding way is as follows: 我当前的编码方式如下:

Frontend: 前端:

<form id="form1" runat="server">

<div class="transbox" id="mainbk" runat="server" style="position:absolute; top:0px; left:0px; width: 100%; height: 100%;" >
  <asp:FileUpload runat="server" ID="UploadImages" style="background-color:white; position:absolute; font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 350px; right: 251px;" Width="500px" AllowMultiple="true"/>
    <asp:Button runat="server" ID="uploadedFile" style="position:absolute;  font-family:'Palatino Linotype'; font-size:medium; top: 4px; left: 870px; width: 112px; height: 29px;" Text="Upload" OnClick="uploadFile_Click" />
    <asp:Panel ID="updtpanel" runat="server" CssClass="transbox" style="width:100%;height:100%;left:0px;top:0px;position:absolute" Visible="false">

    </asp:Panel>
 </div>


</form>

and backend is as follows: 后端如下:

protected void uploadFile_Click(object sender, EventArgs e)
{
    if (UploadImages.HasFiles)
    {
       int tid = 0;

       string fileExt = Path.GetExtension(UploadImages.FileName).ToLower();
       if (fileExt == ".jpeg" || fileExt == ".png" || fileExt == ".jpg" || fileExt == ".bmp")
       {
           HtmlGenericControl d = new HtmlGenericControl("div");
           Button btnsave = new Button();
           btnsave.Text = "Save";


           sb.Append("<div class=" + "\"savback\"" + ">");
           sb.Append("<div class=" + "\"head\"" + ">Write Description</div>");

           foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
           {
               id += 1;
               tid = tid + 1;
               string textid = "txt" + tid;
               filepath = Server.MapPath("~/Images/Gallery/" + uploadedFile.FileName);
               uploadedFile.SaveAs(filepath);
               newpath = "../Images/Gallery/" + uploadedFile.FileName;
               try
               {
                   updtpanel.Visible = true;

                   sb.Append("<div class=" + "\"dataload\"" + ">");
                   sb.Append("<img class=" + "\"loadimg\"" + "src=" + "\"" + newpath.ToString() + "\"" + " />");
                   sb.Append("<textarea  class=" + "\"txtdes\"" + "id=" + "\"" + textid + "\"" + "></textarea>");
                   sb.Append("</div>");


               }

               catch (Exception ex)
               {
                   Response.Write(ex.Message);
               }

           }

           sb.Append("</div>");
           d.InnerHtml = sb.ToString();

           updtpanel.Controls.Add(d);
           updtpanel.Controls.Add(btnsave);
       }
       else
       {
           Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select only Image Files!!');", true);
       }

    }
    else
    {
        Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Please Select a File First!!');", true);        
    }
}

Please let me know which will be the good way of creating dynamic controls?? 请让我知道哪种方法是创建动态控件的好方法?

Optimal code: 最佳代码:

  • Doesn't contain more than 50 lines of difficult to read code (agreed, it's not unreadable, but still, minor refactoring would help), 包含不超过50行难读的代码(同意,它不是不可读的,但是较小的重构还是有帮助的),

  • Doesn't mix CSS with HTML, together with presentation-related HTML attributes such as width , 请勿将CSS与HTML以及与演示文稿相关的HTML属性(例如width

  • Doesn't use the JavaScript alert . 不使用JavaScript alert

Let's get back to your question. 让我们回到您的问题。 Which one is better : StringBuilder or HtmlGenericControl ? 哪个更好StringBuilderHtmlGenericControl

Better being an extremely vague term, let's answer a bunch of slightly different questions: 最好用一个非常模糊的术语,让我们回答一些稍微不同的问题:

  1. Which one is faster ? 哪一个更快

    Probably StringBuilder , given that it doesn't matter. 可能无关紧要的StringBuilder At all. 完全没有 Compared to the time spent downloading an image (say two seconds, ie 2 000 ms.), the comparison in performance between StringBuilder and HtmlGenericControl will be very probably less than a millisecond. 与下载图像所花费的时间(例如2秒,即2 000 ms)相比, StringBuilderHtmlGenericControl之间的性能比较可能不到一毫秒。 Is it important that you waste 1 ms. 浪费1毫秒重要吗? on a process which takes 2 000 ms.? 耗时2000毫秒。

  2. Which one is safer ? 哪一个更安全

    How many errors do you spot in the following code? 您在以下代码中发现多少错误?

     sb.Append("<div class=\\"illustration\\"><span-class=\\"contents\\">") .Append("<img class=" + "\\"loadimg\\"" + "srv=" + "\\"" + newpath + "\\"" + ">") .Append("/div></span>"); 

    Let's see: 让我们来看看:

    • div and span are inverted, divspan反,
    • the closing div is missing the '<' character, 最后的div缺少'<'字符,
    • img is missing '/' (if the output is XHTML), img缺少“ /”(如果输出是XHTML),
    • there is a typo in src written as srv , src有一个错字,写为srv
    • span-class should have been span class , span-class应该是span class
    • there is no space before src ( srv ). srcsrv )前没有空格。

    Nearly every of those mistakes could have been easily avoided by letting .NET Framework the task of generating HTML from strongly typed objects. 通过让.NET Framework执行从强类型对象生成HTML的任务,几乎可以避免这些错误中的每一个。

  3. Which one is more readable ? 哪个更易读

    IMO, neither. IMO,都不是。 HTML code can be written in a clean way, making it extremely readable. HTML代码可以用干净的方式编写,从而使其可读性极强。 In the same way, it would be easy to be lost in all those calls to embedded controls if the code is a piece of crap. 以同样的方式,如果代码有些废话,那么在所有对嵌入式控件的调用中都容易丢失。

  4. Which one is more reliable ? 哪一个更可靠

    .NET Framework is assumed to be heavily tested and particularly reliable, at least compared to average business applications. 至少与普通业务应用程序相比,假定.NET Framework经过了严格的测试,并且特别可靠。 The more you confide to .NET Framework, the better, unless you know how to do better and you've tested your approach, submitted it for pair reviews, etc. 您对.NET Framework的投入越多,它就会越好,除非您知道如何做得更好,并且已经测试了您的方法,将其提交给结对审核等。

    In the case of StringBuilder , you can hardly unit-test your code. 对于StringBuilder ,您几乎无法对代码进行单元测试。 Letting .NET Framework do the HTML generation in your place means that you can concentrate more on the actual objects you manipulate, and testing them is slightly easier. 让.NET Framework代替您的位置来生成HTML,意味着您可以将更多的精力放在处理的实际对象上,并且测试它们会稍微容易一些。

So, what is the single best solution ? 那么, 最好的解决方案是什么?

Personally, if I were stick with classical ASP.NET (by contrast to ASP.NET MVC), I would create a dedicated control with an HTML template . 就个人而言,如果我坚持使用经典的ASP.NET(与ASP.NET MVC相反),则可以使用HTML模板创建专用控件

If for some reasons, this is not possible, then pick HtmlGenericControl : it abstracts the HTML and let you concentrate on the objects themselves. 如果由于某些原因无法实现,则选择HtmlGenericControl :它抽象HTML并让您专注于对象本身。

If you had a requirement to write clean, readable HTML code, HtmlGenericControl would be a burden, and you would have to pick string concatenation or some templating system . 如果您需要编写清晰易读的HTML代码,则HtmlGenericControl将是一个负担,并且您将不得不选择字符串连接或某些模板系统 ASP.NET controls are known for generating not-so-good HTML code. 众所周知,ASP.NET控件会生成不太好的HTML代码。 Given the HTML code in your question, this limitation doesn't apply to your case. 给定问题中的HTML代码,此限制不适用于您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM