[ASP. net mvc] enables html. renderaction to support Lamda expressions

Source: Internet
Author: User

Today, HTML. renderaction is used in ASP. net mvc Code. The Code is as follows:

@{Html.RenderAction("RecentNews")}

It is uncomfortable to specify the action name using a string:

1. The input cannot be intelligently sensed;

2. The error message cannot be displayed in real time.

If there are two unpleasant points, the pleasure of writing code is greatly reduced. The Code is as follows:

@{Html.RenderAction<AggSiteController>(c => c.RecentNews());}

Yes, Lamda. It makes you feel comfortable writing code!

Microsoft won't let us enjoy it, so we can do it ourselves. Write an HTML. renderaction that supports Lamda expressions by yourself. The Code is as follows:

using System.Web.Mvc;using System.Web.Mvc.Html;using System.Linq.Expressions;namespace System.Web.Mvc.Html{    public static class HtmlHelperExtensions    {        public static void RenderAction<TController>(this HtmlHelper htmlHelper,             Expression<Action<TController>> operation)             where TController : Controller        {            var actionName = ((MethodCallExpression)operation.Body).Method.Name;            htmlHelper.RenderAction(actionName);        }    }}

Note: The "(methodcallexpression) operation. Body). method. Name" code comes from get method name from action.

Share an article when to use HTML. renderpartial and HTML. renderaction in ASP. net MVC razor views. Through this article, you can clearly understand HTML. renderpartial and HTML. differences between renderactions.

For example, the latest essay list on the blog homepage is suitable for HTML. renderpartial, while the "News list" on the right is suitable for HTML. renderaction.

A simple understanding is: HTML. renderpartial only uses partialview once (although it can be used multiple times, it is troublesome to upload model every time), HTML. renderaction uses partialview to be used by multiple views (with its own action providing the model ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.