VS2008+MVC的用法总结

ASP.NET MVC Framework 系列(下载)
安装后,新建工程如图:
 
---------------------------------------------------------
基本属性说明:ViewData["VName"]:是用于保存变量,可以在页面上调用,类似于页面缓存。
View():用于跳转页面,View("PageName"):不加后缀名,只有路径就可以[转载]VS2008+MVC的用法总结.
Request.Redirect("PageName")来跳转,ViewData不会保存值。一般用View();来跳转,可以保存值。
----------------------------------
HomeController.cs的属性值:
//有接收表单时,就只有GET方法,用POST会报错。
[AcceptVerbs("GET")]
 public ActionResult WebForm2(string[] chkVal,int? id)
{
            if (Request.HttpMethod.ToUpper() == "POST")
            {
                ViewData["chkVal"] = chkVal.Length;
            }
            return View();
 }
//用于表单的接收的方法
[ActionName("Setting")]
public ActionResult TextForm(string txtVal)
{
          ViewData["chkVal"]=  txtVal;
          //用于保存值,并跳转到指定 页面。[转载]VS2008+MVC的用法总结
          return View("WebForm2");
}
页面上表单:<form action="Setting" id="form1"></form>action指定名要一样。
//返回不同值的,在用Ajax中调用时,就会返回不同的值很有用处。
public ViewResult Text(){}
return Redirect("/Test/ViewPage1");
return RedirectToAction("ViewPage1")
//用于验证表单中有不符合的字符,如<>等。false是就不验证。
[ValidateInput(false)]
//View用来传值[转载]VS2008+MVC的用法总结
public ActionResult Role()
{
DataTable table = new DataTable();
return View(table)
}
前台用<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<DataTable>" %>
ViewPage<>强制泛型类,<% foreach(DataRow row in Model.Rows) %>:Model用来显示指定。
//UpdateModel:用于取得页面上的对象值。要对象名与页面上的名字要一样。[转载]VS2008+MVC的用法总结
MO_Role role = new MO_Role();
this.UpdateModel<MO_Role>(role);
//上传文件方法
#region Demo #3 实现MVC批量上传文件

        public ActionResult Upload()
        {
            return View(@"Upload");
        }

        public ActionResult UploadFiles()
        {
            var r = new List<MikeUploadFile>();

            foreach (string file in Request.Files)
            {
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
                if (hpf.ContentLength == 0)
                    continue;
                string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Upload" , Path.GetFileName(hpf.FileName));
                hpf.SaveAs(savedFileName);

                r.Add(new MikeUploadFile()
                {
                    Name = savedFileName,
                    Length = hpf.ContentLength
                });
            }
            return View(@"Upload", r);
        }

        #endregion
---------------------------------------------------------------------------------------
ActionResult

Action方法返回ActionResult类型的结果。ASP.NET MVC为我们提供了几种ActionResult的实现,如下:

  • ViewResult. 呈现视图页给客户端。由View 方法返回.

  • RedirectToRouteResult. 重定向到另外一个Route。由RedirectToAction 和RedirectToRoute 方法返回.

  • RedirectResult. 重定向到另外一个URL。由 Redirect 方法返回.

  • ContentResult. 返回普通的内容。例如一段字符串。由 Content 方法返回.

  • JsonResult. 返回JSON结果。由 Json 方法返回.

  • EmptyResult. 如果Action必须返回空值,可以返回这个结果。Controller中没有实现的方法,可以return new EmptyResult();.

  • public ActionResult tesx()
            {
                return RedirectToRoute(new { controller="", action="",id="" });
            }//返回的
---------------------------------------------------------------------
//用于页面的继承类,可以在页面加载时判断是否session超时,在viewpage有[转载]VS2008+MVC的用法总结
 
public class BasePage : ViewPage
{
     protected overrider void OnLoad(EventArgs e)
     {
           if (!IsPostBack)
            {
                Response.Cache.SetExpires(DateTime.Now.AddSeconds(3));
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.SetValidUntilExpires(true);
            }
            if (MemberInfo == null)
            {
                Response.Redirect("/Share/Result/-2", true);
            }
            base.OnLoad(e);
     }
}//页面上要继承这个类。
-----------------------------------------------------------------------
//ActionFilterAttribute:用于过滤作用,例如过滤传参数的不正确。。[转载]VS2008+MVC的用法总结
用法[BaseFilter]
public class BaseFilter : ActionFilterAttribute
    {
public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            foreach (var item in filterContext.RequestContext.HttpContext.Request.QueryString.AllKeys)
            {
                string val = filterContext.RequestContext.HttpContext.Request.QueryString[item];
                if (!string.IsNullOrEmpty(val) && IsFitlerSQL(val))
                {
                    filterContext.RequestContext.HttpContext.Response.Redirect("/Share/Result/?msgContent=输入非法字符&msgTltel=失败");

                }
#region Compression
            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding)) return;

            acceptEncoding = acceptEncoding.ToUpperInvariant();

            HttpResponseBase response = filterContext.HttpContext.Response;

            if (acceptEncoding.Contains("GZIP"))
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("DEFLATE"))
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
            

}
----------------------------------------------注意的取值-[转载]VS2008+MVC的用法总结-
//取值<input type="checkbox" name="chkss" value="111"/>
      <input type="checkbox" name="chkss" value="111"/>
      <input type="checkbox" name="chkss" value="111"/>
用this.Request.Form["chkss"];会生成一个用逗号隔开的一个字条串。
----------------------------------------------------------
//上传图片用的类System.Web.HttpPostedFileBase
HttpPostedFileBase StoreBannerUrl
-------------------------------------------
//Global.asax.cs的使用
 public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
   //路由的使用
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

             routes.Add("Fr",
                        new Route("FrPage/{FrPageChild}/{PageName}/index.html",
                                  new Rout_rueDictionary(
                                      new
                                      {
                                          FrPageChild = "FrPageChild",
                                          PageName = "PageName"
                                      }), new Fdays.WebApp.Common.Routing.NewsRoute()
                                 )
                       );
            ///new Fdays.WebApp.Common.Routing.NewsRoute():是一个Route的实现类,在下有实例。[转载]VS2008+MVC的用法总结

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }

        //public static void RegisterRoutes1(RouteCollection routes)
        //{
        //    routes.Add("Uc",
        //                new Route("FrPage/{FrPageChild}/{PageName}/index.html",
        //                          new Rout_rueDictionary(
        //                              new
        //                              {
        //                                  FrPageChild = "FrPageChild",
        //                                  PageName = "PageName"
        //                              }), new Fdays.WebApp.Common.Routing.NewsRoute()
        //                         )
        //               );
        //}

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
            // log4net.Config.XmlConfigurator.Configure();
        }
        List<string> ErrorMessage = new List<string>();
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            // 
        }

     
        protected void Session_Start(Object sender, EventArgs e)
        {
            Application.Lock();
            if (Application["user_sessions"] == null)
            {
                Application["user_sessions"] = 0;
            }
            else
            {
                Application["user_sessions"] = (int)Application["user_sessions"] + 1;
            }
            Application.UnLock();
        }
     
        

        protected void Application_Error(Object sender, EventArgs e)
        {

            Exception exp = Server.GetLastError();
            if (!exp.Message.ToString().Contains("could not be found") && !exp.Message.ToString().Contains("/Views/") && Response.StatusCode != 404 && Response.StatusDescription != "OK")
            {
                #region MyRegion



                if (!ErrorMessage.Contains(exp.ToString()))
                {
                    ErrorMessage.Add(exp.ToString());

                    StringBuilder strE = new StringBuilder();
                    strE.AppendLine("网站路径:" + Request.Url);
                    strE.AppendLine("来源:" + exp.Source);
                    strE.AppendLine("信息:" + exp.Message);
                    if (exp.InnerException != null)
                        strE.AppendLine("内部错误:" + exp.InnerException);
                    strE.AppendLine("堆栈:" + exp.StackTrace);


                    strE.AppendLine("User IP: " + HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] + " &nbsp; " + HttpContext.Current.Request.ServerVariables["REMOTE_HOST"]);
                    strE.AppendLine("User Agent: " + HttpContext.Current.Request.UserAgent);
                    if (HttpContext.Current.Request.UrlReferrer != null)
                        strE.AppendLine("Referrer: " + HttpContext.Current.Request.UrlReferrer.ToString());

                    string mailxml = Server.MapPath("/Mail.xml");
                    System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
                    xmldoc.Load(mailxml);
                    var lista = xmldoc.SelectSingleNode("config");
                    if (lista != null)
                    {
                        if (XML.XmlOperation.GetXmlNodeTextByName(lista.ChildNodes, "IsSend") == "1")
                        {
                            Fdays.Net.Mail.MailSerever mails = new Fdays.Net.Mail.MailSerever();
                            mails.Accoutn = XML.XmlOperation.GetXmlNodeTextByName(lista.ChildNodes, "SenAccoutn");
                            mails.MailAddress = XML.XmlOperation.GetXmlNodeTextByName(lista.ChildNodes, "SendMailAddress");
                            mails.PassWord = Fdays.DES.Decrypt(XML.XmlOperation.GetXmlNodeTextByName(lista.ChildNodes, "SendMailPassWord"), XML.XmlOperation.GetXmlNodeTextByName(lista.ChildNodes, "DecryptKey"));
                            mails.SmtpServer = XML.XmlOperation.GetXmlNodeTextByName(lista.ChildNodes, "SmtpServer");

                            string[] mialaddredd = null;

                            mialaddredd = XML.XmlOperation.GetListXmlNodeTextByName(lista.ChildNodes, "mailAddress");

                            Fdays.Net.Mail.SmtpMail.SendMail(mails, mialaddredd.ToArray(), "品多多出错啦", strE.ToString().Replace("rn", "<br/>"));
                        }
                    }
                }
                #endregion

                Server.ClearError();
                Server.Transfer("/Error.html", false);
            }

        }
--------------------------[转载]VS2008+MVC的用法总结[转载]VS2008+MVC的用法总结[转载]VS2008+MVC的用法总结[转载]VS2008+MVC的用法总结---------------------
//响应用于对Route的进行响影[转载]VS2008+MVC的用法总结
//System.Web.SessionState.IRequiresSessionState特别注意这个,用于把Session在保存,少了无法使用Session.
namespace Fdays.WebApp.Common.Routing
{
    public class NewsRoute : IRouteHandler ,System.Web.SessionState.IRequiresSessionState
    {

        #region IRouteHandler 成员

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new NewsHttpHandler(requestContext);
        }

        #endregion
    }

    public class NewsHttpHandler : IHttpHandler,System.Web.SessionState.IRequiresSessionState
    {
        public RequestContext RequestContext { get; private set; }
        public NewsHttpHandler(RequestContext context)
        {
            this.RequestContext = context;
        }

        #region IHttpHandler 成员

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Server.Execute(string.Format("/FrPage/{0}/{1}.aspx",
                                                RequestContext.RouteData.Values.ContainsKey("FrPageChild")
                                                    ? RequestContext.RouteData.Values["FrPageChild"].ToString()
                                                    : "",
                                                RequestContext.RouteData.Values.ContainsKey("PageName")
                                                    ? RequestContext.RouteData.Values["PageName"].ToString()
                                                    : ""
                                                 )
                                   );
        }

        #endregion
    }
}
-------------------------------------------------------------------
System.Web.MVC.HtmlHelper Html用来生成前台页面的Html标签。
<% Html.RenderPartial("LogOnUserControl"); %>是调用自定义控件的方法,自定义控件要在View文件夹中
不然会找不到。
---------------------------------
拦截器接口(IActionFilter,IExceptionFilter,IResultFilter,IAuthorizationFilter) 与ActionFilterAttribute配合使用
http://www.cnblogs.com/bboy/archive/2010/02/17/1668941.html【说明】
using System.Web.Mvc;
 using System.Collections.Generic;
 using System.IO;
 namespace FilterDemo.Controllers
 {
     public class TestOrderAttribute : FilterAttribute, IResultFilter, IActionFilter, IAuthorizationFilter, IExceptionFilter
     {
         #region IResultFilter 成员
 
         public void OnResultExecuted(ResultExecutedContext filterContext)
         {
             Write( "OnResultExecuted");
             
         }
 
         private static void Write(string methodName)
         {
             StreamWriter sw = new StreamWriter("c:\test.txt",true);
             sw.WriteLine(methodName);
             sw.Close();
         }
 
         public void OnResultExecuting(ResultExecutingContext filterContext)
         {
             Write( "OnResultExecuting");
         }
 
         #endregion
 
         #region IActionFilter 成员

         public void OnActionExecuted(ActionExecutedContext filterContext)
         {
             Write( "OnActionExecuted");
         }
 
         public void OnActionExecuting(ActionExecutingContext filterContext)
         {
             Write( "OnActionExecuting");
         }
 
         #endregion
 
         #region IAuthorizationFilter 成员
 
         public void OnAuthorization(AuthorizationContext filterContext)
         {
             Write("OnAuthorization");
         }
 
         #endregion
 
         #region IExceptionFilter 成员
 
         public void OnException(ExceptionContext filterContext)
         {
             Write("OnException");
             filterContext.ExceptionHandled = true;
         }
 
         #endregion
     }
 
 }
---------------------------[转载]VS2008+MVC的用法总结[转载]VS2008+MVC的用法总结[转载]VS2008+MVC的用法总结[转载]VS2008+MVC的用法总结[转载]VS2008+MVC的用法总结[转载]VS2008+MVC的用法总结-------------------------------------
ViewData和TempData的区别

虽然ViewData和TempData都可以传递弱类型数据,但是两者的使用是有区别的:

  ViewData的生命周期和View相同, 只对当前View有效.

  TempData保存在Session中, Controller每次执行请求的时候会从Session中获取TempData并删除Session, 获取完TempData数据后虽然保存在内部的字典对象中,但是TempData集合的每个条目访问一次后就从字典表中删除. 也就是说TempData的数据至多只能经过一次Controller传递, 并且每个元素至多只能访问一次.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值