0

I have a program with login and logout. I have an exercise class, I have a create view that allows me to create exercises that are composed by name, photo, video. I fill the form in View Create and when I click create this error appears to me

NullReferenceException: Object reference not set to an instance of an object.
WebApplication1.Controllers.ExerciciosGinasiosController.Create(ExerciciosGinasio exerciciosGinasio, IFormFile fotografia, IFormFile video) in ExerciciosGinasiosController.cs

            string nome_ficheiro = Path.GetFileName(fotografia.FileName);

In the exercise class I have

 [Table("Exercicios_Ginasio")]
    public partial class ExerciciosGinasio
    {
        public ExerciciosGinasio()
        {
            Inclui = new HashSet<Inclui>();
        }

        [Key]
        [Column("IDExercicios_Ginasio")]
        public int IdexerciciosGinasio { get; set; }
        [Required]
        [Column("nome")]
        [StringLength(30)]
        public string Nome { get; set; }
        [Required]
        [Column("texto_descritivo")]
        [StringLength(1000)]
        public string TextoDescritivo { get; set; }
        [Required]
        [Column("foto")]

        public string Foto { get; set; }
        [Required]
        [Column("video")]

        public string Video { get; set; }

        [InverseProperty("IdexerciciosGinasioNavigation")]
        public virtual ICollection<Inclui> Inclui { get; set; }
    }
}

In the controller belonging to the Exercises class (ExercisesController) I have this method in order to create a new exercise

 [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("IdexerciciosGinasio,Nome,TextoDescritivo,Foto,Video")] ExerciciosGinasio exerciciosGinasio, IFormFile fotografia,IFormFile video)
        {
            string caminho = Path.Combine(_hostEnviroment.ContentRootPath, "wwwroot\\Exercicios");

            string nome_ficheiro = Path.GetFileName(fotografia.FileName);
            string caminho_completo = Path.Combine(caminho, nome_ficheiro);

            FileStream fs = new FileStream(caminho_completo, FileMode.Create);
            fotografia.CopyTo(fs);
            exerciciosGinasio.Foto = caminho_completo;
            fs.Close();




            string caminho2 = Path.Combine(_hostEnviroment.ContentRootPath, "wwwroot\\Exercicios");

            string nome_ficheiro2 = Path.GetFileName(video.FileName);
            string caminho_completo2 = Path.Combine(caminho2, nome_ficheiro2);

            FileStream _fs = new FileStream(caminho_completo2, FileMode.Create);
            video.CopyTo(_fs);
            exerciciosGinasio.Video = caminho_completo2;
            _fs.Close();

            if (ModelState.IsValid)
            {

                _context.Add(exerciciosGinasio);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(exerciciosGinasio);
        }

And in the view of this method I have

@model WebApplication1.Models.ExerciciosGinasio

@{
    ViewData["Title"] = "Create";
}


<h4>Criar Exercicio</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Nome" class="control-label"></label>
                <input asp-for="Nome" class="form-control" />
                <span asp-validation-for="Nome" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="TextoDescritivo" class="control-label"></label>
                <input asp-for="TextoDescritivo" type="text" class="form-control" />
                <span asp-validation-for="TextoDescritivo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Foto" class="control-label"></label>
                <input asp-for="Foto" type="file" class="form-control" accept=".png, .jpg, .bmp" value="" />
                @*<span asp-validation-for="Foto" class="text-danger"></span>*@

                <div>
                    <input type="hidden" name="fotografia" value="0" />
                </div>
                <div class="form-group">
                    <label asp-for="Video" class="control-label"></label>
                    <input asp-for="Video" type="file" class="form-control" />
                    @*<span asp-validation-for="Video" class="text-danger"></span>*@
                </div>
                <div>
                    <input type="hidden" name="video" value="0" />
                </div>
                <div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
        </form>
    </div>
</div>
<br />

<div>
    <a asp-action="Index" asp-controller="Home">Voltar</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Does anyone know what may be causing this error? And how can I solve

rsd_17
  • 75
  • 1
  • 5
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Progman Jan 29 '20 at 18:49

1 Answers1

0

NullReferenceException: Object reference not set to an instance of an object.

string nome_ficheiro = Path.GetFileName(fotografia.FileName);

In your View page, we can find you are using hidden field(s) with default value 0 for fotografia and video, but your Create action expects file via IFormFile object, if you debug your code, you would find fotografia is null, which would casue exception while you read FileName property of fotografia.

To fix it, you can modify the code like below.

Inputs of Photo and Video

<div class="form-group">
    <label asp-for="Foto" class="control-label"></label>
    <input type="file" class="form-control" name="fotografia" accept=".png, .jpg, .bmp" />
</div>
<div>
    <input type="hidden" name="Foto" value="0" />
</div>
<div class="form-group">
    <label asp-for="Video" class="control-label"></label>
    <input type="file" name="fvideo" class="form-control" />
</div>
<div>
    <input type="hidden" name="Video" value="0" />
</div>

Controller Action

[HttpPost]
public IActionResult Create([Bind("IdexerciciosGinasio,Nome,TextoDescritivo,Foto,Video")] ExerciciosGinasio exerciciosGinasio, 
    IFormFile fotografia, 
    IFormFile fvideo)
{
    string nome_ficheiro = Path.GetFileName(fotografia.FileName);

    //code logic here

        
    return View(exerciciosGinasio);
}  

Test Result

enter image description here

Community
  • 1
  • 1
Fei Han
  • 26,415
  • 1
  • 30
  • 41