简体   繁体   中英

How to make an Asp.Net Core form with file upload?

I am creating a registration form for a user, using a viewmodel. Besides entering data such as Username, email and password, the user must also upload an image.

When the user is finished entering the data and the viewmodel is send to the action method, something interesting happens.

The file is null, but all the other data is correct.

This is the viewmodel:

public class RegisterAsBusiness
{   
    public string UserName { get; set; }
    public IFormFile FormFile { get; set; }
    public string Email { get; set; }
}

This is the Html part:


@model AfsluttendeProject.Models.ViewModels.RegisterAsBusiness


<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="RegisterAsBusiness">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="UserName" class="control-label"></label>
                <input asp-for="UserName" class="form-control" />
                <span asp-validation-for="UserName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <dl>
                    <dt>
                        <label asp-for="FormFile"></label>
                    </dt>
                    <dd>
                        <input asp-for="FormFile" type="file">
                    </dd>
                </dl>

            </div>

  <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>

            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>


And the methods in the controller:


public IActionResult RegisterAsBusiness()
{
    return View(new RegisterAsBusiness());
}

[HttpPost]
public async Task<IActionResult> RegisterAsBusiness(RegisterAsBusiness registration)
{
    return RedirectToAction("Login");
}

在您的表单中,您应该添加enctype="multipart/form-data"您应该检查它的含义以及为什么需要

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM