MVC控制器使用总结

一、新手入门

1.特性

[AuthorizeFilter]  用于权限过滤

[HttpGet]  

[HttpPost]

2.参数

GET获取

       [HttpGet]
        public ActionResult Get(int id=0)
        {
            return Json("test",JsonRequestBehavior.AllowGet);
        }

返回字符串 "test"

POST提交

[HttpPost]
public ActionResult void Post(Model model)
{
  var result = new Result();
   if (ModelState.IsValid && model != null)
   {
  }
   return Json(result);
}

上传图片

[HttpPost]
public ActionResult void Post(Model modelName, FormCollection form)
{
    var requestFiles = Request.Files;//HttpFileCollectionBase
    if (requestFiles.Count > 0)
    {
        for (int i = 0; i < requestFiles.Count; i++)
        {
            //此块代码仅作示例
            //文件名称 requestFiles[i].FileName 
            var postedfile =  requestFiles[i];//HttpPostedFileBase
            var savePath="d://d.jpg";
            postedfile.SaveAs(savePath);
        }
    }
   return Json(result, "text/html", Encoding.UTF8);
}

 

3.返回类型(返回方法)

return null;//返回Null或者Void数据类型的EmptyResult
return View();//返回与本控制器同名的视图
return View(model);//返回与本控制器同名的视图,并传model到视图
return View("Success");//返回指定的视图
return View("~/Views/Shared/Success.cahtml");//返回指定的视图的路径 return View("Success",model);//返回指定的视图,并传model到视图 return Json(result, JsonRequestBehavior.AllowGet);//一般由给post或ajax提交的请求,返回json return Content("Test Content", "text/html"); // 可指定文本类型 return JavaScript("alter('hello');"); //在客户端执行的脚本,但并不会直接响应弹出窗口,需用页面再一次调用 string fileName = "~/Content/test.zip"; // 文件名 string downFileName = "文件显示名称.zip"; // 要在下载框显示的文件名 //返回FileResult要写入响应中的二进制输出,一般可用作简单下载 return File(fileName, "application/octet-stream", downFileName); //重定向方法:Redirect / RedirectToAction / RedirectToRoute return Redirect("http://www.baidu.com"); //直接转到指定的url地址 return RedirectToAction("index","home",new{id="1"});//跳转到指定的控制器 return RedirectToRoute("Default", new { controller = "Home", action = "Index"}); //指定路由进行跳转

 

推荐文章:

http://www.cnblogs.com/artech/archive/2012/08/13/action-result-01.html

 

二、常见问题

1.下拉框默认值不选中

如代码:

@Html.DropDownListFor(model => model.Status, (List<SelectListItem>)ViewBag.StatusList, new { @class = "form-control" }) 

解决:

在控制器中为 model.Status赋默认值

 

posted @ 2015-07-30 17:01  心存善念  阅读(813)  评论(0编辑  收藏  举报