Fileupload works in Index action only (ASP.Net MVC

2019-09-05 06:50发布

问题:

I have simple controller with two actions:

public class TestController : Controller
{
      // /Test
      public ActionResult Index()
      {
          return View();
      }
      [HttpPost]
      public ActionResult Index(HttpPostedFileBase file)
      {    
          bool b = file == null; //there will be false
          return RedirectToAction("Index");
      }

      // /Test/Wonder
      [HttpGet]
      public ActionResult Wonder()
      {
          return View();
      }        
      [HttpPost]
      public ActionResult Wonder(HttpPostedFile file)
      {
          bool b = file == null; //there will be TRUE!
          return RedirectToAction("Wonder");
      }
}

I have similar views for my actions. Index action:

<h2>Index</h2>
<form action="" method="post" enctype="multipart/form-data">  
  <input type="file" name="file" id="file" />
  <input type="submit" />
</form>

Wonder action:

<h2>It's wonder!</h2>
<form action="" method="post" enctype="multipart/form-data">  
  <input type="file" name="file" id="file" />
  <input type="submit" />
</form>

Why does first form (Index) submit correct file to controller, but second form (Wonder) submits null to controller?

回答1:

Your Index ActionResult receives as a parameter a HttpPostedFileBase object whereas the Wonder ActionResult receives as a parameter a HttpPostedFile object.