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的现象。
另外一种写法:
4、MVC中使用log4net
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");
}