Detailed Description: Use asp.net mvc to render html, asp. netmvc
To improve user experience, we generally use ajax to load data and then render html based on the data. html Rendering can be implemented using front-end rendering and server-side rendering.
Frontend Rendering
The front-end template engine or MVC framework, such as the template of underscore. js, or angular. js framework, can be used to splice html without any framework.
<! DOCTYPE html>
Backend Rendering
If asp.net mvc is used, some views can be used. ajax loads some rendered views on the server side directly. For all the code, visit my github.
public ActionResult News() { return View(); } public ActionResult RenderNews(int pageIndex = 1, int pageSize = 10) { return PartialView(); }
The front-end directly sends an ajax request to RenderNews
$.ajax({ url: '/Home/RenderNews?pageIndex=3&pageSize=10', type: "POST", beforeSend: function() { }, complete: function() { }, success: function(result) { if (result.trim() != "") { $("#containter").html(result); } }, error: function(e) { console.log(e); }});
In this way, the backend outputs the rendered html directly. Sometimes we need to return the error code to the front end, for example, {"code": 10000, "message": "successful ", "data": "<p> aaaaa </p>"}, You need to dynamically call the distribution view in the controller to get the rendering result. The dynamic call code is:
Public abstract class BaseController: controller {// <summary> /// dynamic rendering distribution view /// </summary> /// <param name = "viewName"> View name </param>/ // <param name = "model"> model </param> // <returns> rendered html </returns> public virtual string RenderPartialViewToString (string viewName, object model) {if (string. isNullOrEmpty (viewName) viewName = this. controllerContext. routeData. getRequiredString ("action"); this. viewData. model = model; using (var sw = new StringWriter () {ViewEngineResult viewResult = System. web. mvc. viewEngines. engines. findPartialView (this. controllerContext, viewName); var viewContext = new ViewContext (this. controllerContext, viewResult. view, this. viewData, this. tempData, sw); viewResult. view. render (viewContext, sw); return sw. getStringBuilder (). toString ();}}}
Summary
Because the backend rendering can use the asp.net mvc template engine syntax, it is better in Maintainability and development efficiency than in front-end rendering. I personally prefer to use backend rendering, but because it needs to be passed to the browser html, therefore, the bandwidth usage is high, which can be solved by increasing the server bandwidth.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.