.Net Core MVC Web App - passing value from View to Controller in a Form not working

336 views Asked by At

I've read other posts on here to try and fix my issue but no luck.

I have a form, that is based on a simple model.

public class Image
{       
    public string FileName { get; set; }
    public string ImagePath { get; set; }

}

In my view, I have a form which displays an image:

@model Uploader.Models.Image

<h1>View Image</h1>



<form asp-controller="Images" asp-action="Download" method="post" enctype="multipart/form-data">

    <img src="~/Images/@Model.FileName" />


    <input type="submit" value="Download Image" class="btn btncolour btn-primary" />

    @Model.FileName

</form>

That last Model.Filename, I was just testing to see if the value is present (which it is). From what i can see, everything is fine here, when I submit this form, the values from my model (specifically Image.FileName) should be posted back to the server.

my controller method:

    [HttpPost]
    public async Task<IActionResult> Download(Image image)
    {
        if (image.FileName == null)
            return Content("filename not present");

        var path = Path.Combine(
                       Directory.GetCurrentDirectory(),
                       "wwwroot", image.FileName);

        var memory = new MemoryStream();
        using (var stream = new FileStream(path, FileMode.Open))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        return File(memory, GetContentType(path), Path.GetFileName(path));
    }

My code hits this method upon postback, but image.FileName is always null, even though on the View itself, I can see that model.FileName does contain a value.

Could anyone explain what I am doing wrong?

many thanks

1

There are 1 answers

2
Zoran Stankovic On BEST ANSWER

FileName is used for src of image but not as an input. Only input field values are sent in request when you click submit.

Try adding text input with name="FileName", then enter some value and click submit. Then you should be able to receive this value in controller method.