Asp.net MVC Razor template engine tips

Source: Internet
Author: User

Razor is the new default template type in Asp.net MVC, and its syntax is simple and easy to use. This article does not involve Razor syntax. It mainly introduces some of Razor's usage skills in MVC projects and how to use Razor in an MVC environment. reading Directory: 1. Relationship between Razor and MVC 2. Extension of Razor in MVC 3. Use Razor in MVC to generate Html fragments 4. Remove from MVC, use Razor as the template engine independently. the relationship between Razor and MVC: Razor is the default template engine in MVC and ASPX template engine in MVC. in earlier versions of MVC, The ASPX template engine is used by default. When a View File is added by default, you can see two template engines in MVC by default. Image you can also introduce other template engines to the MVC project. The MVCContrib Project is a project that extends MVC. The project address is: http://mvccontrib.codeplex.com Here is a list of template engines that can be extended in MVC. Template-engines in short, what we want to talk about here is that the template engines are independent, they are even independent projects, developed by different companies and organizations. You can use the template engine you are familiar with in MVC. The following describes how to use Razor in MVC. 2. in MVC, expand Razor to search for the template. See the Action Method in the Controller below: copy the code public class TestController: Controller {public ActionResult Index () {return View ();}} copy the Code. This is a simple Action method Index. The return View () method redirects the process to View Engine for processing. If we do not create a View \ Test \ Index. the following error page is displayed for the cshtml file: view-not-found-error. It is easy to see from the above. By default, the view types, aspx, ascx, cshtml, and vbhtml supported by MVC are supported. and the path rule for finding the corresponding View is :~ View/{Controller}/{Action }~ View/Shared/{Action}. However, in actual development, the default View path is used to completely limit the View hierarchy, which is not suitable for the development of complex projects. For example, in the Shared View folder, you want to be subdivided into Partial, Common, Email, and EditorTemplate. For example, in the folder corresponding to each Controller, you want to add a folder named Partial, used to store view files that present a part of a page. You only need to add several lines of code in the Application_Start method in the Global. asax. cs file. Copy the Code protected void Application_Start (){................... ViewEngines. Engines. Add (new RazorViewEngine {PartialViewLocationFormats = new [] {"~ /Views/{1}/Partial/{0}. cshtml ","~ /Views/Shared/Partial/{0}. cshtml ","~ /Views/Shared/Common/{0}. cshtml ","~ /Views/Shared/Email/{0}. cshtml ","~ /Views/Shared/EditorTemplate/{0 }. cshtml "}});} copy the code above. {1} is Controller, and {0} corresponds to Action. take a look at the figure below. We can see that there are many other extension points, such as Area and FileExtensions. You can try it. Viewengine_extension 3. in MVC, Ajax is often used to partially refresh pages when Razor is used to generate Html string projects. If you only need to refresh a local area, it is relatively simple. You can use a corresponding Action to respond to Ajax requests, obtain the refreshed html content. What should I do if I need to refresh multiple regions on the page? At this time, we want the results returned by the background to be in a Json format similar to this. Copy the return Json code (new {Success = true, Message = "Sucess", HtmlPart1 = ........ HtmlPart2 = ....... }, JsonRequestBehavior. to solve this problem, you can easily use the following Controller extension method: copy the public static class ControllerExtension {// <summary> // Renders a (partial) view to string. /// </summary> /// <param name = "controller"> Controller to extend </param> /// <param name = "viewName"> (Partial) view to render </param> // <returns> Rendered (partial) view as string </returns> public static string RenderPartialViewToString (this ControllerBase controller, string viewName) {return controller. renderPartialViewToString (viewName, null);} // <summary> // Renders a (partial) view to string. /// </summary> /// <param name = "controller"> Controller to extend </param> /// <param name = "viewName"> (Partial) view to render </param> /// <param name = "model"> Model </param> /// <returns> Rendered (partial) view as string </returns> public static string RenderPartialViewToString (this ControllerBase controller, string viewName, object model) {if (string. isNullOrEmpty (viewName) viewName = controller. controllerContext. routeData. getRequiredString ("action"); controller. viewData. model = model; using (var sw = new StringWriter () {var viewResult = ViewEngines. engines. findPartialView (controller. controllerContext, viewName); var viewContext = new ViewContext (controller. controllerContext, viewResult. view, controller. viewData, controller. tempData, sw); viewResult. view. render (viewContext, sw); return sw. getStringBuilder (). toString () ;}} copy the code. Then, replace the returned result with: copy the code return Json (new {Success = true, Message = "Sucess", HtmlPart1 = this. renderPartialViewToString ("_ HtmlPart1", model1), HtmlPart2 = this. renderPartialViewToString ("_ HtmlPart2", model2),}, JsonRequestBehavior. allowGet); copy the Code 4. from MVC, Razor is used as the template engine independently. RazorEngine is an independent open-source project. The project address is https://github.com/Antaris/RazorEngine It is a template engine encapsulated based on Microsoft's Razor and can be used independently. That is to say, the Razor template function is retained, but Razor is separated from Asp.net MVC and can be used in other application environments. I usually generate Email text here. Of course, someone is also used as a code generator. Easy to use: string template = "Hello @ Model. Name! Welcome to Razor! "; String result = Razor. Parse (template, new {Name =" World "}); the result above is" Hello World! Welcome to Razor !" 5. other articles are mainly used in Razor to share some learned knowledge. you can search for the content without Razor syntax. There are many articles on the Internet. Some personal opinions on the code generator. When I saw the code generator, I thought it was a good thing and it could reduce the workload. Later, after in-depth study, I found that the necessity was not very great. If many code in the program needs to be generated, most of the Code may be repeated and similar, the Code should be refactored and streamlined through the design pattern. To avoid using code generators, you can not only streamline the code, but also open another door for you.

Related Article

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.