zoukankan      html  css  js  c++  java
  • Asp.net MVC知识积累

     一、知识积累

    1.Controller中的ViewBag.key= value可以作为回传参数,在视图return PartialView("分部视图", 数据)中,通过 @ViewBag.addColName调用

    2.合理利用隐藏标签存值<input type="hidden" id="sql" value="@ViewBag.sql" />

    3.视图通过Model传值给分部视图    

    视图控制器ViewBag.OrderField = orderField;   return View("Index", model);    视图Index中@Html.Partial("_highRefListsPager", Model)   <input id="orderFieldHidden" type="hidden" value="@ViewBag.OrderField"/>

    4.使用Bundle 减少请求数

    一个页面有很多图片 、JavaScript 和 CSS 要加载进来, 获取每一个资源浏览器都要发起一个请求(不考虑缓存),请求多的话,网页加载的速度肯定不快,于是我们考虑到去减少请求数,最简单的方法是把JS和CSS文件合并,但是,合并以后,破坏了原有的文件结构,况且不同的页面需要不同的文件组合。那么,能不能根据需要动态组合文件呢,ASP.NET的Bundle为我们解决了这个问题。

    5.页面布局采用div包裹分部视图的方式   

    <div>@Html.Partial("分部视图", Model)</div>

    6.布局

    @section header {
        @RenderSection("header", required: false)
    }
    @Html.Partial("_headerAnalyzer")
    @RenderBody()
    @Html.Partial("_footer")
    @section FooterScripts {
        @RenderSection("FooterScripts", required: false)
    }

     7.缓存

    [OutputCache(Duration = AppSettings.OutputCacheTime)]
    public ActionResult HighRefInit()
     {
          return View("Index", model);        
     }

    8.多个out参数 

     class Program
        {
            static void Main(string[] args)
            {
                int a=1,b, c;
                Out(a,out b,out c);
                Console.WriteLine(string.Format("a={0},b={1},c={2}",a.ToString(), b.ToString(), c.ToString()));
                Console.ReadKey();
            }
            public static int Out(int a,out int b,out int c)
            {
                b = a + 1;
                c = a + 2;
                return a;
            }
    
        }

    结果:a=1,b=2,c=3 

    9.Dictionary性能最好

    HashSet<T>
    IList<T> fn = new List<T>();
    Dictionary<T, T> fnList = new Dictionary<T, T>(); 

    10.获取程序的基目录:System.AppDomain.CurrentDomain.BaseDirectory

    11.Stopwatch类

    Stopwatch watch = new Stopwatch();
    watch.Start();
    //处理代码
    watch.Stop();
    Console.WriteLine("
    耗费时间:" + watch.ElapsedMilliseconds);

    12.获得Jquery对象的规范写法

     var $obj = $("#Id");

    判断对象是否存在采用$("#Id").Lengrh>0

    13.FTP
    http://www.cnblogs.com/name-lh/archive/2007/04/28/731528.html

    14.TempData

    要实现跨Action的变量传递有就不能用ViewBag了,你可以用Session,TempData。Session是整个网站会话级别的,生命周期比较长,如果要存一次性的数据用Session有点浪费,所以这里建议用TempData,因为TempData可以做为Controller或者Action跳转时的临时存储变量或数据的容器。

    public class HomeController : Controller  
      {  
          public ActionResult Index()  
          {  
              TempData["D"] = "WT";  
              return Redirect("Index1");  
          }  
      
          public ActionResult Index1()  
          {  
              return Redirect("Index2");  
          }  
      
          public ActionResult Index2()  
          {  
              return Redirect("Index3");  
          }  
      
      
          public ActionResult Index3()  
          {  
              ContentResult result = new ContentResult();  
      
              result.Content = TempData["D"].ToString();  
      
              return result;  
          }  
      }  
    输入 Home/Index,此时发现页面已经跳转到:Home/Index3,且输出“WT”。似乎说明:说明TempData会保留未使用的值,并不是说"TempData只存放一次数据,到第三个Action时,第一个Action存放的数据就失效了"。

    15.构建View实体Model

    public class PagerViewInfo<T, R>
        {
            public List<T> List { get; set; }
            public R Param { get; set; }
        }
    
        public class PagerViewDataTable<Dt, R>
        {
            public DataTable DT { get; set; }
            public R Param { get; set; }
            public string Flag { get; set; }
        }

    16.灵活构建xml配置

    17.TempData,ViewData和ViewBag的比较

    18.有时需要在ASP.NET MVC4的视图的@model中使用多个类型的实例,.NET Framework 4.0版本引入的System.Tuple类可以轻松满足这个需求。

      Controller

      public ActionResult Index()
            {
                User user = new User() { Name="mf", Status=1 };
                HydUser hydUser = new HydUser() { Name="沐风", Status=1 };
                return View(Tuple.Create(user, hydUser));// 返回一个Tuple对象,Item1代表user、Item2代表hydUser
            }

      View

    @model Tuple<CommonFoundation.Model.User, CommonFoundation.Model.HydUser>  
    <h2>@Model.Item1.Name </h2>
    <h2>@Model.Item2.Name </h2>

    19.通过方法@Html.Action("IndexSub", "Home")缓存指定的局部视图

    [OutputCache(Duration = 60 * 60 * 24)]
    public ActionResult IndexSub()
    {
        return PartialView(list);
    }

    20.Html.Action、html.ActionLink与Url.Action的区别

      1)html.ActionLink返回的指向指定controller、指定action的超链接标签<a>标签.如果没有指定controller,则默认为本页面对应的Controller.

      如@Html.ActionLink(“链接文本”、“someaction”、“somecontroller”,new { id = " 123 " },null)
      生成:
      < a href = " / somecontroller / someaction / 123 " >链接文本</a>

      2)Html.Action可以执行一个控制器的action,并将返回结果作为html string。

      3)Url.Action返回的是指定控制器指定action的完整URL地址,不含<a>标签

    21. return HttpNotFound();

    22.view:默认会先搜索与Controller同名的目录,如果搜索不到,就会改为搜索Shared目录,所以可以将公用的view放到Shared目录。

    23.return new EmptyResult()或者 return;不需要回传任何数据。

    24.JavaScriptResult

    public ActionResult JavaScript()
     {
       return JavaScript("alert('Hello World!');");
     }

    25.@Url.Action("Index", "Home", new { Area = "" }) 

    26.Html.RenderAction

    允许你直接调用某一个Action,并把返回的结果直接显示在当前调用的View中。比如:@{Html.RenderAction("Show", "Tag");} 此时,TagController中的Show方法会被调用。由于这时调用的是一个Action方法,因此可以在此方法中完成你想要完成的各种操作,比如从数据库,文件等获取数据,写数据等并返回结果。

    [OutputCache(Duration = 24 * 60 * 60)]
    public ActionResult GetFeedMsg()
    {
         return Content("ok");
    }

    27.TimeSpan 

    DateTime endTime = userAcQuery.CreatTime;
    DateTime nowTime = DateTime.Now;
    TimeSpan ts = nowTime.Subtract(endTime);
    int hours =Convert.ToInt32(ts.TotalHours);

    28.敏感词过滤

    29.MVCExtend

    public static class MVCExtend
        {
            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();
                }
            }
        }

    30.try...catch...finally

            try
            {
               
            }
            catch(Exception ex)
            {
               
            }
            finally
            {
              
            }

    31.@Html.Partial

    1 <div class="sareaCot" id="sareaCot_CotAdv">
    2 @{
    3    Dictionary<string, Object> returnParam = (Dictionary<string, Object>)ViewBag.Param;             
    4  }
    5   @Html.Partial("_CotAdv", returnParam)
    6 </div>

    32.mysql

    1  MySqlService mysqlHelper = new MySqlService(mysqlConnectionString);
    2  List<User> user= mysqlHelper.ExecuteModelList("SELECT * FROM USER   LIMIT   20", null, ModelFromDataRow);
    3  private User ModelFromDataRow(DataRow dr)
    4    {
    5      return DataRowToModel.ToModel<User>(dr);
    6    }

    34.Application.DoEvents();

    private void button1_Click(object sender, EventArgs e)
            {
                int seek = 0; ;
                string insertSql = string.Empty;
                int totalCount=10000;
                for (int i = 0; i < totalCount; i++)
                {
                    seek++;
                    lblStatus.Text = string.Format("处理标签,共 :{0},已处理:{1})", totalCount, seek.ToString());
                    Application.DoEvents();
                }
            }

    35. jQuery live 重复绑定,导致多次执行的解决方式

    //先通过die()方法解除,再通过live()绑定  
    $(“#selectAll”).die().live(“click”,function(){  
    //事件运行代码  
    });  
    

    36. 利用JS设置默认图片

    <img src="@Model.PicPath" alt="作者照片" title="作者照片" onerror="javascript:this.src='@Url.Content("~/Content/images/default.jpg")'"/>

    37.推荐使用ViewBag

    38.可以直接键入 prop + 两次 TAB 键,就可以快速完成属性的编写

    39..net析构函数

            #region Dispose
            /// <summary> 
            /// 清理所有正在使用的资源。
            /// </summary>
            /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
            #endregion

    40.同一sessionid不能并发,session锁

    41.C# String.Format格式化json字符串中包含"{" "}"报错问题

      json.Append(String.Format("{"total":{0},"row":{1}}", lineCount, strJSON));直接会报错

      字符串中包含{或者},则需要用{{ 来代替字符 {,用}} 代替 }

      如:json.Append(String.Format("{{"total":{0},"row":{1}}}", lineCount, strJSON));

    42.List去重

     string CYNAME1 = "安徽经济年鉴;安徽经济年鉴;安徽经济年鉴;安徽经济年鉴";
     IList<string> list = CYNAME1.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList().Distinct().ToList();
     string  joinStr= string.Join(";", list);

    43.Tuple类型

    44.ASP.net Session阻塞、Session锁、MVC Action请求阻塞问题

        可以为本Controller增加以下特性,但是本Controller都不能修改Session了,只能读取

        [SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]

    45.SortedDictionary<string, object>(StringComparer.Ordinal);

    46.iis7 发布mvc 遇到的HTTP错误 403.14-Forbidden Web 服务器被配置为不列出此目录的内容

    iis 7上发布mvc报错:403.14-Forbidden Web 服务器被配置为不列出此目录的内容

    折腾了半天,提示里面的解决方法是:

    • 如果不希望启用目录浏览,请确保配置了默认文档并且该文件存在。
    • 使用 IIS 管理器启用目录浏览。
      1. 打开 IIS 管理器。
      2. 在“功能”视图中,双击“目录浏览”。
      3. 在“目录浏览”页上,在“操作”窗格中单击“启用”。
    • 确认站点或应用程序配置文件中的 configuration/system.webServer/directoryBrowse@enabled 特性被设置为 True。

    按照该方法改后 ,发现网页运行界面进去的变成了目录结构,后来发现改配置文件web.config配置文件的配置节后,网站就可以正常使用了,记录下哦。

    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true" /> 
    </system.webServer>

    要设置<modules>节的值为true, 而目录浏览启用或禁用其实都没影响的。

    47.解决Web部署 svg/woff/woff2字体 404错误

     打开服务器IIS管理器,找到MIME类型。

     添加MIME类型 添加三条:  

           文件扩展名      MIME类型 

    .svg             image/svg+xml
    .woff            application/x-font-woff
    .woff2          application/x-font-woff

    48.以最高级模式渲染文档

    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">

    49.string.IsNullOrEmpty 和 string.IsNullOrWhiteSpace的区别

    string.IsNullOrEmpty方法是判断字符串是否为:null或者string.Empty;string.IsNullOrWhiteSpace方法是判断null或者所有空白字符,功能相当于string.IsNullOrEmpty和str.Trim().Length总和。

    50.ASP.NET MVC中如何使用RenderSection渲染节点

        @RenderBody():呈现子页的主体内容

      @RenderSection():呈现特别的节部分。

      HelperResult RenderSection(string name, bool required = true);

      required默认为true必须覆写,设为false则为可选覆写;

    https://blog.csdn.net/sgear/article/details/37599883

    51.远程服务器返回错误: (405) 不允许的方法

    使用微软的东西,经常会遇到误导人的错误。

    这次在将站点从IIS 7.5迁移至IIS 8.0后,调用Web Service(.asmx)时出现错误提示:远程服务器返回错误: (405) 不允许的方法。

    这个问题竟然是因为IIS 8.0默认没有添加*.svc的映射。

    解决方法:

    进入Server Manager->Add Roles and Features Wizard->Features,在.NET Framework 4.5功能->WCF服务中选中“HTTP激活”(HTTP Activation),完成安装后,问题解决。

     52.刷新dns

        由于本次升级涉及ip地址变化、http重定向为https等内容,因此在升级完成后如果仍然访问如鹏网有问题,请尝试命令行执行“ipconfig /flushdns”来刷新dns,并且清空浏览器缓存。

    53.'2018-06-020 08:00:00' 转2018062008

    select FORMAT(CONVERT(datetime,'2018-06-020 08:00:00'),'yyyyMMddHH') AS sortDate

    54.mvc自定义全局异常处理

    <system.web>
    <!--添加customErrors节点 定义404跳转页面-->
     <customErrors mode="On">
          <error statusCode="404" redirect="/Error/Path404" />
        </customErrors>
     </system.web>
    //Global文件的EndRequest监听Response状态码
    protected void Application_EndRequest()
    {
      var statusCode = Context.Response.StatusCode;
        var routingData = Context.Request.RequestContext.RouteData;
        if (statusCode == 404 || statusCode == 500)
        {
          Response.Clear();
           Response.RedirectToRoute("Default", new { controller = "Error", action = "Path404" });
        }
    }

    55.HttpActionContext

    actionContext.Request.Properties[Key] = stopWatch;
    
    Stopwatch stopWatch = actionContext.Request.Properties[Key] as Stopwatch;

      

  • 相关阅读:
    neo4j通过LOAD CSV导入结点和关系
    二叉树的几种遍历方法
    数据结构之二叉排序树
    结合数据结构来看看Java的String类
    变量和对象
    Java虚拟机的内部体系结构
    算法

    freemarker
    solr的安装和启动
  • 原文地址:https://www.cnblogs.com/cnki/p/5216933.html
Copyright © 2011-2022 走看看