How to return the value of an HttpPostedFileBase in a Post method of the MVC Controller C #

0

I have a model like the following:

public class Model_ejemplo
{
   public HttpPostedFileBase image { get; set; }
}

in my controller I receive my model with this property

[HttpPost]
public ActionResult index(Model_ejemplo Model)
{
   Return view(Model);
}

in my view this is the form where I capture my file

@using (Html.BeginForm("Index", "MyController", FormMethod.Post, new { id = "formulario", enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(x => x.image, new {type= "file", @id = "image", accept ="image/x-png,image/gif,image/jpeg"})
}

The problem is that whenever I return the model in the post action of the controller it arrives as Null in my view, and I need to return this type of data after it has not passed the validations of my action.

    
asked by Elvin Acevedo 21.05.2018 в 15:55
source

2 answers

0

Hi, I recommend this approach, create your view in the following way

@using (Html.BeginForm("Index", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <input type="file" name="image" />
    <input type="submit" name="Submit" id="Submit" value="Upload" />
}

Then define your action in the controller like this (I'll define you an example)

[HttpPost]  
public ActionResult Index(HttpPostedFileBase file)  
{  
    if (file != null && file.ContentLength > 0)  
        try 
        {  
            string path = Path.Combine(Server.MapPath("~/Images"),  
                                       Path.GetFileName(file.FileName));  
            file.SaveAs(path);  
            ViewBag.Message = "File uploaded successfully";  
        }  
        catch (Exception ex)  
        {  
            ViewBag.Message = "ERROR:" + ex.Message.ToString();  
        }  
    else 
    {  
        ViewBag.Message = "You have not specified a file.";  
    }  
    return View();  
}
    
answered by 22.05.2018 в 12:09
0

try decorating the image property with [DataType (DataType.Upload)]. That is:

    public class Model_ejemplo
{
   [DataType(DataType.Upload)]
   public HttpPostedFileBase image { get; set; }
}
    
answered by 23.05.2018 в 16:16