asp.net MVC gets the Dynamic HTML code for a view in the controller

Source: Internet
Author: User
Tags contains net object model return string static class string format domain name


If we need dynamic Ajax from the server to get HTML code, stitching strings is a bad way, so we write the HTML code in the cshtml file, and then through the code into the model, dynamically get cshtml in the HTML code



Of course, we want to use the common method to get cshtml, we must rewrite the Razorviewengine view engine, configure the view search location



When looking for a view, the Razor view engine follows the conventions established by earlier versions of the MVC framework. For example, if you request the index view associated with the home controller, Razor will review the list of views such as:



~/views/home/index.cshtml
~/views/home/index.vbhtml
~/views/shared/index.cshtml
~/views/shared/index.vbhtml



As you now know, Razor does not actually look up these view files on disk because they have not been compiled into C # classes. Razor looks for compiled classes that represent these views. The. cshtml file is the template that contains the C # statement (which we are using), and the. vbhtml file contains Visual Basic statements.



You can change this view file of razor search by generating a razorviewengine subclass. This class is the iviewengine implementation of the razor. It is built on a set of base classes that define a set of properties that determine which view file to search for. These properties are described in the table.


Property
Property
Description
Describe
Default Value
Default value
Viewlocationformats
Masterlocationformats
Partialviewlocationformats
The locations to look for views, partial views, and layouts
Find the location of views, partial views, and layouts
"~/views/{1}/{0}.cshtml",
"~/views/{1}/{0}.vbhtml",
"~/views/shared/{0}.cshtml",
"~/views/shared/{0}.vbhtml"
Areaviewlocationformats
Areamasterlocationformats
Areapartialviewlocationformats
The locations to look for views, partial views, and layouts for
Find the location of a region's views, partial views, and layouts
"~/areas/{2}/views/{1}/{0}.cshtml",
"~/areas/{2}/views/{1}/{0}.vbhtml",
"~/areas/{2}/views/shared/{0}.cshtml",
"~/areas/{2}/views/shared/{0}.vbhtml"


These attributes precede the introduction of razor, which is why each group of three properties has the same value. Each property is an array of strings that are represented by a composite string format symbol. The following are the parameter values corresponding to the placeholders:
{0} represents the name of the view.
{0} represents view name
{1} represents the name of the controller.
{1} indicates controller name
{2} represents the name of the area.
{2} represents the domain name of the zone
To modify the search location, you will generate a new class that derives from Razorviewengine and modify one or more of the property values described in the table.



Create a new Customrazorviewengine class in the Infrastructure folder


Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.Mvc;

Namespace MvcApplication1.Infrastructure
{
     Public class CustomRazorViewEngine : RazorViewEngine
     {
         Public CustomRazorViewEngine()
         {

             ViewLocationFormats = new string[] {

                 "~/Views/{1}/{0}.cshtml",
                  "~/Views/Shared/{0}.cshtml",
                   "~/Views/Shared_PartialView/{0}.cshtml"//Specify the path to find a file
             };

             PartialViewLocationFormats = new string[] {

                 "~/Views/{1}/{0}.cshtml",
                  "~/Views/Shared/{0}.cshtml",
                   "~/Views/Shared_PartialView/{0}.cshtml"////Specify the path to find a file
             };
         }

     }
}


We register our derived view engine with the Viewengines.engines collection in the Global.asax Application_Start method, like this:


protected void Application_Start ()
{
arearegistration.registerallareas ();
ViewEngines.Engines.Clear ();

VIEWENGINES.ENGINES.ADD (New Customrazorviewengine ());


Webapiconfig.register (globalconfiguration.configuration);
Filterconfig.registerglobalfilters (globalfilters.filters);
Routeconfig.registerroutes (routetable.routes);
Bundleconfig.registerbundles (bundletable.bundles);
}


Gets the method of the HTML string and how to invoke the


public class HomeController : Controller
    {
        //
        // GET: /Home/
     

        public ActionResult Index()
        {
            string html =  this.ControllerContext.RenderViewToString("_CommonPartial", new UserViewModel() {  UserName="haha"});
            return View(new UserViewModel() { IsEnable = false, UserCode = "aa" });
        }



      



    }

    public static class HelperExtensions
    {
        public static string RenderViewToString(this ControllerContext context, string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = context.RouteData.GetRequiredString("action");

            context.Controller.ViewData.Model = model;

            using (var sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
                var viewContext = new ViewContext(context,
                                                  viewResult.View,
                                                  context.Controller.ViewData,
                                                  context.Controller.TempData,
                                                  sw);
                try
                {
                    viewResult.View.Render(viewContext, sw);
                }
                catch (Exception ex)
                {
                    throw;
                }

                return sw.GetStringBuilder().ToString();
            }
        }
    } 


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.