C# 如何将文件上载到asp.net?

C# 如何将文件上载到asp.net?,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我正在寻找一个解决方案,如何发送一个文件使用表单到asp应用程序。我写的是asp.net框架MVC Razor 我的表格: <div class="container"> <div class="col-md-2"> @using (Html.BeginForm("Data", "Admin", FormMethod.Post, new { encrypte = "multipart/form-data"})) {

我正在寻找一个解决方案,如何发送一个文件使用表单到asp应用程序。我写的是asp.net框架MVC Razor

我的表格:

<div class="container">
    <div class="col-md-2">
        @using (Html.BeginForm("Data", "Admin", FormMethod.Post, new { encrypte = "multipart/form-data"}))
        {
            <div class="form login-form">
                <label for="username" class="text-info">Wczytaj plik:</label>
                <input type="file" name="file" id="file" />
            </div>
            <div id="register-link" class="text-right">
                <input type="submit" class="btn btn-success" value="Importuj" />
            </div>
            @ViewBag.Message
        }
    </div>
</div>

不幸的是,上面的代码不起作用,我是不是做错了什么,是否有其他选项可以将文件上载到asp?

我认为有输入错误,我建议您使用
ActionResult
而不是
ViewResult

打字错误是:
new{enctype=“multipart/form data”}
not
new{encrypt=“multipart/form data”})

示例代码:

查看

@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { 
enctype="multipart/form-data"}))  
{  
    <div>  
        @Html.TextBox("file", "", new {  type= "file"}) <br />  
        <input type="submit" value="Upload" />  
        @ViewBag.Message  
    </div>     
}

请参考下面的链接,这会让您更好地理解


希望这一定会对您有所帮助。

“上述代码不起作用”是否有错误?你收到成功的信息了吗?你试过调试吗?我没有错误。所以我调试了代码:我加载文件并发送表单,在控制器中传递的对象为空并返回到原始视图。
@using(Html.BeginForm("UploadFile","Upload", FormMethod.Post, new { 
enctype="multipart/form-data"}))  
{  
    <div>  
        @Html.TextBox("file", "", new {  type= "file"}) <br />  
        <input type="submit" value="Upload" />  
        @ViewBag.Message  
    </div>     
}
    [HttpPost]  
    publicActionResultUploadFile(HttpPostedFileBase file)  
    {  
        try  
        {  
            if (file.ContentLength > 0)  
            {  
                string _FileName = Path.GetFileName(file.FileName);  
                string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);  
                file.SaveAs(_path);  
            }  
            ViewBag.Message = "File Uploaded Successfully!!";  
            return View();  
        }  
        catch  
        {  
            ViewBag.Message = "File upload failed!!";  
            return View();  
        }  
    }