如何克服我对ASP中的恐惧?净MVC标记?

时间:2021-04-24 07:31:59

So I totally buy into the basic tenents of ASP.NET, testability, SoC, HTML control...it's awesome. However being new to it I have a huge hang up with the markup. I know it comes from my hatred of classic ASP, and I can't help but feel like I've entered the twilight zone when I see this.

所以我完全相信ASP的基本原理。NET、可测试性、SoC、HTML控件…这是可怕的。不管我对它有多么陌生,我都对这个标记有很大的兴趣。我知道它来自于我对经典ASP的厌恶,当我看到这个的时候,我不禁觉得我已经进入了一个模糊的区域。

I don't know what the alternative is (can I use server controls, databinding etc...?)

我不知道另一种选择是什么(我可以使用服务器控件、数据绑定等等)吗?

12 个解决方案

#1


11  

There are things you can do to help clean up the markup, but I agree it can get a bit tag-soupy.

您可以做一些事情来帮助清理标记,但是我同意它可能会变得有点像标签。

  • You can make your own HTML helpers to output data using extension methods, so you can hide away some of the if/else logic, iteration, etc
  • 您可以使用扩展方法使您自己的HTML助手输出数据,因此您可以隐藏一些if/else逻辑、迭代等。
  • Strongly type your views so you can do ViewData.Model.myProperty rather than (MyClasst)ViewData["foo"].myProperty
  • 强烈地键入视图,这样就可以执行ViewData.Model。myProperty而不是(MyClasst)视讯系统“foo”.myProperty

For instance this is an extension I made to make an RSS-spitter-outer :)

例如,我做了一个扩展来创建一个RSS-spitter-outer:)

  public static string RSSRepeater<T>(this HtmlHelper html, IEnumerable<T> rss) where T : IRSSable
    {
        StringBuilder result = new StringBuilder();

        if (rss.Count() > 0)
        {
            foreach (IRSSable item in rss)
            {
                result.Append("<item>").Append(item.GetRSSItem().InnerXml).Append("</item>");
            }
        }

        return result.ToString();
    }

So in my front end all I have is <%=Html.RSSRepeater(mydata)%> which is much nicer.

所以在我的前端,我只有<% Html.RSSRepeater(mydata)%>,这更好。

#2


7  

1) Helpers reduce HTML noise
2) Partial Views to break up larger pages/reuse view code
3) Try a different rendering engine, such as Sparkline
4) REFACTOR if your view includes too many if statements.

帮助减少HTML噪音2)局部视图分解更大的页面/重用视图代码3)尝试不同的呈现引擎,如Sparkline 4)重构,如果你的视图包含太多if语句。

#3


4  

Avoiding tag soup reading might be helpful. Generally you can not use server controls (some might work though), there is no postback or viewstate. I don't think you can use databinding (again there might be exceptions, I'm not sure how ASP.NET MVC treats server controls in the view.) - the easiest method to "databind" something is to pass a list or array of data into the view and use foreach to build HTML out of it.

避免读标签汤可能会有帮助。一般来说,您不能使用服务器控件(尽管有些可以工作),没有回发或viewstate。我认为您不能使用数据绑定(同样也有例外,我不确定ASP如何使用。NET MVC将服务器控件放在视图中。)-“databind”最简单的方法是将列表或数据数组传递到视图中,并使用foreach来构建HTML。

#4


1  

Move some (not all, only in cases it makes sense) display logic (like your dates) into your model. For instance, in your example you could add a Task.DisplayDate string property that handles the .ToShortDateString() call. Then if it ever changes, you change it all in one place and it shortens up the code in the view.

移动一些(不是全部,只有在有意义的情况下)显示逻辑(比如你的日期)到你的模型中。例如,在您的示例中,您可以添加一个任务。用于处理. toshortdatestring()调用的DisplayDate字符串属性。如果它改变了,你可以在一个地方改变它,它会缩短视图中的代码。

HTML helpers are nice, sometimes. I don't really like having my HTML in concatenated strings or a StringBuilder in a class somewhere, but if you're doing something a lot that works with a lot of different sets of data they're not so bad.

HTML助手有时候很不错。我不喜欢把HTML放在串连字符串中或者类中的StringBuilder中,但是如果你做了很多与不同数据集相关的事情,它们也不是那么糟糕。

I would also change your C# code formatting preferences to have brackets on the same line. That cuts down the clutter. Unfortunately you can't have separate settings for this between the code editor and the HTML editor, so you'll have to get used to it in your code too. It's not the worst thing in the world.

我还将您的c#代码格式化首选项更改为在同一行的括号。这样可以减少杂乱。不幸的是,在代码编辑器和HTML编辑器之间不能有单独的设置,所以您必须在代码中也习惯它。这不是世界上最糟糕的事情。

What others have said helps too: use partial views and strong-typing.

其他人所说的也有帮助:使用部分视图和强类型。

#5


1  

I like to make the syntax highlighting for my "<% %>" tags very similar to the background color. I use a black background and a silver-ish (don't have the specific colour on hand atm) colour for my "<% %>" tags. That plus the other suggestions here should have make your code more readable. Of course, you can always try another view engine (that's the beauty of MVC!)

我喜欢使“<% >”标签的语法高亮显示与背景颜色非常相似。我使用黑色背景和银色(没有特定颜色的手atm)颜色为我的“<% %>”标签。再加上这里的其他建议,您的代码应该更易于阅读。当然,您可以尝试另一个视图引擎(这就是MVC的美妙之处!)

#6


1  

I would look at some of the other View engines available, I personally really like Spark view engine but there are many others out there.

我想看一些其他的视图引擎,我个人很喜欢Spark View engine但是还有很多其他的视图引擎。

Scott Hanselman did a great post looking at spark and Nhaml with some snippets of markup that you can look at to see if it fits your asthetics :)

Scott Hanselman做了一篇很好的文章,研究了spark和Nhaml的一些代码片段,你可以看看它是否适合你的美学。

http://www.hanselman.com/blog/TheWeeklySourceCode30SparkAndNHamlCrazyASPNETMVCViewEngines.aspx

http://www.hanselman.com/blog/TheWeeklySourceCode30SparkAndNHamlCrazyASPNETMVCViewEngines.aspx

#7


0  

If you press ctrl+z after it formats it just undoes the formatting and not the typing.

如果你在格式化后按ctrl+z,它只会取消格式化,而不是输入。

I find this helpful to keep the first bracket on the same line as the if statement

我发现这有助于使第一个括号与if语句保持一致

#8


0  

If you're talking about the HTML from rendered controls, I'm afraid it doesn't get any better just because you've got a nice standards-based wrapper around your View in MVC. Without adapted controls, the output is still circa-1995 crappy nested table code.

如果您正在讨论呈现控件的HTML,恐怕它不会变得更好,因为您在MVC中已经有了一个很好的基于标准的包装器。如果没有经过调整的控件,输出仍然是大约1995年糟糕的嵌套表代码。

Thanks, Microsoft!

谢谢,微软!

#9


0  

use server side comments <%-- comment --%> to separate blocks and increase readability. use extra line spacing to separate blocks too (SO seems to be killing off my line spacing here for some reason).

使用服务器端注释<%——注释-%>来分离块并增加可读性。使用额外的行间距来分隔块(因此,出于某种原因,这里的行间距似乎被取消了)。

        <%-- Go through each testimonial --%>
        <% foreach (var testimonial in ViewData.Model.Testimonials) { %>

        <div class="testimonialFrame">
            <div class="testimonialHeader"><%= testimonial.summaryText %></div>


            <%-- Show video if available --%>
            <% if (string.IsNullOrEmpty(testimonial.Video.FullURL) == false) { %>

            <div  style="padding-top:12px">
                <% Html.RenderAction("YouTubeControl", "Application", new { youTubeId = testimonial.Video.FullURL }); %>
            </div>

            <% } %>

            <div class="roundedBox" style="margin-top:15px">
                <div id="txtTestimonialText" class="testimonialText paddedBox"><%= testimonial.TestimonialText %></div>
            </div>

            <div class="testimonialFooter"><%= testimonial.name %></div>
        </div>

        <% } %>

#10


0  

Very occasionally use helper methods (I'm NOT talking about the extension helper methods) to write HTML code in the view itself using the Html object model. I wouldnt recomment this unless you have some wierd logic that you cant easily write in the view. As long as the code in .aspx.cs is VIEW code then its fine.

使用HTML对象模型在视图中编写HTML代码时,偶尔会使用助手方法(我不是在说扩展助手方法)。我不会重述这一点,除非您有一些难以在视图中编写的强大逻辑。只要。aspx中的代码。cs是视图代码,它很好。

In your View's .aspx file :

在您的视图的。aspx文件中:

 <%-- render section --%>
 <% RenderTextSection(section); %>

In your View's 'codebehind' you use HtmlGenericControl to create HTML and then the following line to write it out :

在你的视图的'codebehind'中,你使用HtmlGenericControl创建HTML,然后用下面一行写出来:

htmlControl.RenderControl(new HtmlTextWriter(Response.Output));

My full method :

我的完整的方法:

protected void RenderTextSection(ProductSectionInfo item)

    {
        HtmlGenericControl sectionTextDiv = new HtmlGenericControl("div");

        bool previousHasBulletPoint = false;
        System.Web.UI.HtmlControls.HtmlControl currentContainer = sectionTextDiv;

        foreach (var txt in item.DescriptionItems)
        {
            if (!previousHasBulletPoint && txt.bp)
            {
                // start bulleted section
                currentContainer = new HtmlGenericControl("UL");
                sectionTextDiv.Controls.Add(currentContainer);
            }
            else if (previousHasBulletPoint && !txt.bp)
            {
                // exit bulleted section
                currentContainer = sectionTextDiv;
            }

            if (txt.bp)
            {
                currentContainer.Controls.Add(new HtmlGenericControl("LI")
                {
                    InnerHtml = txt.t
                });
            }
            else
            {
                currentContainer.Controls.Add(new HtmlGenericControl()
                {
                    InnerHtml = txt.t
                });
            }

            previousHasBulletPoint = txt.bp;
        }

        sectionTextDiv.RenderControl(new HtmlTextWriter(Response.Output));
    }

#11


0  

I'd suggest looking at the Velocity templating engine that MonoRails used. ASP.NET MVC models itself very closely on the MonoRails format, so using the Velocity templates is fairly easy.

我建议看一下单轨列车使用的速度模板引擎。ASP。NET MVC对单轨格式进行了非常紧密的建模,因此使用Velocity模板相当容易。

Click here to learn more.

点击这里了解更多信息。

#12


0  

Well now you could try out Razor (in ASP.NET MVC 3)

现在你可以试试Razor(在ASP里)。净MVC 3)

I just hope that the "@" won't scare you too :P

我只是希望“@”不会吓到你:P

#1


11  

There are things you can do to help clean up the markup, but I agree it can get a bit tag-soupy.

您可以做一些事情来帮助清理标记,但是我同意它可能会变得有点像标签。

  • You can make your own HTML helpers to output data using extension methods, so you can hide away some of the if/else logic, iteration, etc
  • 您可以使用扩展方法使您自己的HTML助手输出数据,因此您可以隐藏一些if/else逻辑、迭代等。
  • Strongly type your views so you can do ViewData.Model.myProperty rather than (MyClasst)ViewData["foo"].myProperty
  • 强烈地键入视图,这样就可以执行ViewData.Model。myProperty而不是(MyClasst)视讯系统“foo”.myProperty

For instance this is an extension I made to make an RSS-spitter-outer :)

例如,我做了一个扩展来创建一个RSS-spitter-outer:)

  public static string RSSRepeater<T>(this HtmlHelper html, IEnumerable<T> rss) where T : IRSSable
    {
        StringBuilder result = new StringBuilder();

        if (rss.Count() > 0)
        {
            foreach (IRSSable item in rss)
            {
                result.Append("<item>").Append(item.GetRSSItem().InnerXml).Append("</item>");
            }
        }

        return result.ToString();
    }

So in my front end all I have is <%=Html.RSSRepeater(mydata)%> which is much nicer.

所以在我的前端,我只有<% Html.RSSRepeater(mydata)%>,这更好。

#2


7  

1) Helpers reduce HTML noise
2) Partial Views to break up larger pages/reuse view code
3) Try a different rendering engine, such as Sparkline
4) REFACTOR if your view includes too many if statements.

帮助减少HTML噪音2)局部视图分解更大的页面/重用视图代码3)尝试不同的呈现引擎,如Sparkline 4)重构,如果你的视图包含太多if语句。

#3


4  

Avoiding tag soup reading might be helpful. Generally you can not use server controls (some might work though), there is no postback or viewstate. I don't think you can use databinding (again there might be exceptions, I'm not sure how ASP.NET MVC treats server controls in the view.) - the easiest method to "databind" something is to pass a list or array of data into the view and use foreach to build HTML out of it.

避免读标签汤可能会有帮助。一般来说,您不能使用服务器控件(尽管有些可以工作),没有回发或viewstate。我认为您不能使用数据绑定(同样也有例外,我不确定ASP如何使用。NET MVC将服务器控件放在视图中。)-“databind”最简单的方法是将列表或数据数组传递到视图中,并使用foreach来构建HTML。

#4


1  

Move some (not all, only in cases it makes sense) display logic (like your dates) into your model. For instance, in your example you could add a Task.DisplayDate string property that handles the .ToShortDateString() call. Then if it ever changes, you change it all in one place and it shortens up the code in the view.

移动一些(不是全部,只有在有意义的情况下)显示逻辑(比如你的日期)到你的模型中。例如,在您的示例中,您可以添加一个任务。用于处理. toshortdatestring()调用的DisplayDate字符串属性。如果它改变了,你可以在一个地方改变它,它会缩短视图中的代码。

HTML helpers are nice, sometimes. I don't really like having my HTML in concatenated strings or a StringBuilder in a class somewhere, but if you're doing something a lot that works with a lot of different sets of data they're not so bad.

HTML助手有时候很不错。我不喜欢把HTML放在串连字符串中或者类中的StringBuilder中,但是如果你做了很多与不同数据集相关的事情,它们也不是那么糟糕。

I would also change your C# code formatting preferences to have brackets on the same line. That cuts down the clutter. Unfortunately you can't have separate settings for this between the code editor and the HTML editor, so you'll have to get used to it in your code too. It's not the worst thing in the world.

我还将您的c#代码格式化首选项更改为在同一行的括号。这样可以减少杂乱。不幸的是,在代码编辑器和HTML编辑器之间不能有单独的设置,所以您必须在代码中也习惯它。这不是世界上最糟糕的事情。

What others have said helps too: use partial views and strong-typing.

其他人所说的也有帮助:使用部分视图和强类型。

#5


1  

I like to make the syntax highlighting for my "<% %>" tags very similar to the background color. I use a black background and a silver-ish (don't have the specific colour on hand atm) colour for my "<% %>" tags. That plus the other suggestions here should have make your code more readable. Of course, you can always try another view engine (that's the beauty of MVC!)

我喜欢使“<% >”标签的语法高亮显示与背景颜色非常相似。我使用黑色背景和银色(没有特定颜色的手atm)颜色为我的“<% %>”标签。再加上这里的其他建议,您的代码应该更易于阅读。当然,您可以尝试另一个视图引擎(这就是MVC的美妙之处!)

#6


1  

I would look at some of the other View engines available, I personally really like Spark view engine but there are many others out there.

我想看一些其他的视图引擎,我个人很喜欢Spark View engine但是还有很多其他的视图引擎。

Scott Hanselman did a great post looking at spark and Nhaml with some snippets of markup that you can look at to see if it fits your asthetics :)

Scott Hanselman做了一篇很好的文章,研究了spark和Nhaml的一些代码片段,你可以看看它是否适合你的美学。

http://www.hanselman.com/blog/TheWeeklySourceCode30SparkAndNHamlCrazyASPNETMVCViewEngines.aspx

http://www.hanselman.com/blog/TheWeeklySourceCode30SparkAndNHamlCrazyASPNETMVCViewEngines.aspx

#7


0  

If you press ctrl+z after it formats it just undoes the formatting and not the typing.

如果你在格式化后按ctrl+z,它只会取消格式化,而不是输入。

I find this helpful to keep the first bracket on the same line as the if statement

我发现这有助于使第一个括号与if语句保持一致

#8


0  

If you're talking about the HTML from rendered controls, I'm afraid it doesn't get any better just because you've got a nice standards-based wrapper around your View in MVC. Without adapted controls, the output is still circa-1995 crappy nested table code.

如果您正在讨论呈现控件的HTML,恐怕它不会变得更好,因为您在MVC中已经有了一个很好的基于标准的包装器。如果没有经过调整的控件,输出仍然是大约1995年糟糕的嵌套表代码。

Thanks, Microsoft!

谢谢,微软!

#9


0  

use server side comments <%-- comment --%> to separate blocks and increase readability. use extra line spacing to separate blocks too (SO seems to be killing off my line spacing here for some reason).

使用服务器端注释<%——注释-%>来分离块并增加可读性。使用额外的行间距来分隔块(因此,出于某种原因,这里的行间距似乎被取消了)。

        <%-- Go through each testimonial --%>
        <% foreach (var testimonial in ViewData.Model.Testimonials) { %>

        <div class="testimonialFrame">
            <div class="testimonialHeader"><%= testimonial.summaryText %></div>


            <%-- Show video if available --%>
            <% if (string.IsNullOrEmpty(testimonial.Video.FullURL) == false) { %>

            <div  style="padding-top:12px">
                <% Html.RenderAction("YouTubeControl", "Application", new { youTubeId = testimonial.Video.FullURL }); %>
            </div>

            <% } %>

            <div class="roundedBox" style="margin-top:15px">
                <div id="txtTestimonialText" class="testimonialText paddedBox"><%= testimonial.TestimonialText %></div>
            </div>

            <div class="testimonialFooter"><%= testimonial.name %></div>
        </div>

        <% } %>

#10


0  

Very occasionally use helper methods (I'm NOT talking about the extension helper methods) to write HTML code in the view itself using the Html object model. I wouldnt recomment this unless you have some wierd logic that you cant easily write in the view. As long as the code in .aspx.cs is VIEW code then its fine.

使用HTML对象模型在视图中编写HTML代码时,偶尔会使用助手方法(我不是在说扩展助手方法)。我不会重述这一点,除非您有一些难以在视图中编写的强大逻辑。只要。aspx中的代码。cs是视图代码,它很好。

In your View's .aspx file :

在您的视图的。aspx文件中:

 <%-- render section --%>
 <% RenderTextSection(section); %>

In your View's 'codebehind' you use HtmlGenericControl to create HTML and then the following line to write it out :

在你的视图的'codebehind'中,你使用HtmlGenericControl创建HTML,然后用下面一行写出来:

htmlControl.RenderControl(new HtmlTextWriter(Response.Output));

My full method :

我的完整的方法:

protected void RenderTextSection(ProductSectionInfo item)

    {
        HtmlGenericControl sectionTextDiv = new HtmlGenericControl("div");

        bool previousHasBulletPoint = false;
        System.Web.UI.HtmlControls.HtmlControl currentContainer = sectionTextDiv;

        foreach (var txt in item.DescriptionItems)
        {
            if (!previousHasBulletPoint && txt.bp)
            {
                // start bulleted section
                currentContainer = new HtmlGenericControl("UL");
                sectionTextDiv.Controls.Add(currentContainer);
            }
            else if (previousHasBulletPoint && !txt.bp)
            {
                // exit bulleted section
                currentContainer = sectionTextDiv;
            }

            if (txt.bp)
            {
                currentContainer.Controls.Add(new HtmlGenericControl("LI")
                {
                    InnerHtml = txt.t
                });
            }
            else
            {
                currentContainer.Controls.Add(new HtmlGenericControl()
                {
                    InnerHtml = txt.t
                });
            }

            previousHasBulletPoint = txt.bp;
        }

        sectionTextDiv.RenderControl(new HtmlTextWriter(Response.Output));
    }

#11


0  

I'd suggest looking at the Velocity templating engine that MonoRails used. ASP.NET MVC models itself very closely on the MonoRails format, so using the Velocity templates is fairly easy.

我建议看一下单轨列车使用的速度模板引擎。ASP。NET MVC对单轨格式进行了非常紧密的建模,因此使用Velocity模板相当容易。

Click here to learn more.

点击这里了解更多信息。

#12


0  

Well now you could try out Razor (in ASP.NET MVC 3)

现在你可以试试Razor(在ASP里)。净MVC 3)

I just hope that the "@" won't scare you too :P

我只是希望“@”不会吓到你:P