HTTPPostedFileBase always return null in controller

强颜欢笑 提交于 2019-12-02 17:23:22

问题


I have checked various answer for this, but none of them works for me, my code in .cshtml is as follows:

<input type="file" name="PostedNRLFile" />

and then in controller I have

 public JsonResult SaveRecord(NewAuditLetterViewModel viewModel, FormCollection all, string hvalue, HttpPostedFileBase PostedNRLFile)

Which is always null, Please help me in this.

I have already tried few things like creating a property in viewmodel, this is also null. Also used new { enctype = "multipart/form-data", id = "documentForm" } in my beginform tag. Also checked their is only one tag in source.


回答1:


You have to add enctype = "multipart/form-data" in form tag.

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, 
                               new { enctype = "multipart/form-data" }))

Try this c# code in controller action

if (Request.Files != null && Request.Files.Count > 0)
{
    HttpPostedFileBase file = Request.Files[0];
    if (file != null && file.ContentLength > 0)
    {
    }
}

You have to retrieve the file.




回答2:


try this one:

var fileCount = Request.Files.Count;
if (fileCount > 0)
{
 for (int i = 0; i < (fileCount); i++)
    { 
        HttpPostedFileBase Yourfile= Request.Files[i] as   HttpPostedFileBase;
        // do whatever with your file
    }
}



回答3:


if you want to use MVC to upload file you need: - create form and have to set tag: enctype = "multipart/form-data" - create input with name same HttpPostedFileBase in controller



来源:https://stackoverflow.com/questions/32218971/httppostedfilebase-always-return-null-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!