MVC 3 学习笔记及小技巧

1、MVC中的区域:使用它的目的在于让我们的系统结构分层等很清晰,同时也有利于系统分工协作。
2、MVC 页面(Areas)跳转:比如直接在浏览器重输入http://localhost/Admin/Account/Login/,想在登陆成功后跳转到http://localhost/Admin/Home/,代码如下:
return RedirectToAction("Index", "Home", new { area = "Admin" });

3、Upload小技巧:

Views端的代码:

<form method="post" enctype="multipart/form-data" action="/Common/UpLoadFile/" >
      <input type="file" id="uploadfile" name="uploadfile"/>
      <input type="submit" value="提交" />
</form>

Controller端代码

[HttpPost]
 public ActionResult UpLoadFile( HttpPostedFileBase uploadfile)
 {
     return View();
 }
在此需要注意的是,方法中参数名必须跟<input type="file" ...>中的name名称一致,否则会出现File一直是null的现象。
另外一种写法:
 public ActionResult Index()
  {
    foreach (string upload in Request.Files)
    {
      if (!Request.Files[upload].HasFile()) continue;
      string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
      string filename = Path.GetFileName(Request.Files[upload].FileName);
      Request.Files[upload].SaveAs(Path.Combine(path, filename));
    }
    return View();
  }

4、MVC中使用log4net
配置和用法都和webform差不多,Controller中的写法:
  log4net.ILog log = log4net.LogManager.GetLogger("MvcMusicStoreError"); 
        // GET: /Log4netTest/Test/ 
        public ActionResult Index()
        {
            string error = string.Empty;
            error += "发生异常页: " + Request.Url.ToString() ;  
            log.Error(error); 
            return View();
        }


5、MVC中返回Json

Controller中的写法

 public ActionResult GetProvinceList()
        {
            //验证请求
            //if (!Request.IsAjaxRequest())
            //{
            //    return Content("请不要非法方法,这是不道德的行为!");
            //} 
            var modellist = new List<string>();
            modellist.Add("tessss1");
            modellist.Add("tessss2");
            modellist.Add("tessss3");
            modellist.Add("tessss4");
            //此请求已被阻止,因为当用在 GET 请求中时,会将敏感信息透漏给第三方网站。若要允许 GET 请求,请将 JsonRequestBehavior 设置为 AllowGet。
            return Json(modellist,JsonRequestBehavior.AllowGet);
        }

在此需要注意的是:需要引用using System.Web.Mvc.Ajax;

6、MVC中的验证码的实现


Controller中的主要代码

 //
        // GET: /Common/VerificationCode/
        public ActionResult GetValidateCode()
        {

            string code = CreateRandomCode(4);
            Session["ValidateCode"] = code;
            byte[] bytes = CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        } 



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值