Reputation: 71
I try to make @Html.EditorFor(model => model.file)
to put file on web page (file is IFormFile
type) in my ASP.NET Core application. But file is null
, when i click submit,for some reason, and exception arises.For string everything is OK. Here is HTML code:
@using (Html.BeginForm("tt", "Home", FormMethod.Post))
{
<div class="row">
<div class="col-md-4">
@Html.EditorFor(model => model.file)
</div>
<div class="col-md-8">
<button type="submit" id="btnUpload" class="btn btn-primary">Upload</button>
</div>
</div>
<br />
<div>@Html.DisplayFor(model => model.content)</div>
}
controller code:
public ActionResult tt(Models.FileInfo f)
{
var r = f.content1 + f.file.FileName;
f.content = r;
return View("Demo_index", f);
}
and model:
public class FileInfo
{
public IFormFile file { get; set; }
public string content { get; set; }
public string content1 { get; set; }
}
Is it possible to make @Html.EditorFor(model => model.file)
work? Or is there some similar way to make form with file uploading?
Upvotes: 1
Views: 1051
Reputation: 239290
The issue is that you're posting as x-www-form-urlencoded
, which doesn't support file uploads. You need to use multipart/form-data
, instead, which can be achieved via adding the enctype
attribute to your form tag:
<form ... enctype="multipart/form-data">
This is possible using Html.BeginForm
, but you have to use an overload that requires you to specify a ton of parameters, and it's more pain than it's worth. Besides, in Core, using the tag helpers is much better anyways. Literally all you need is:
<form asp-action="tt" asp-controller="Home" method="post" enctype="multipart/form-data">
...
</form>
If you're doing a postback, i.e. to the same page you're already on, you can remove the asp-action
and asp-controller
attributes entirely. This will be processed by the built-in FormTagHelper
and the right action and such will be generated for you.
FWIW, the same applies with your input as well. Instead of EditorFor
, you can simply do:
<input asp-for="file" />
The InputTagHelper
will fill in everything else.
Upvotes: 3