locked
How to get my image back in my form "<input type="file" " when i post my form and i got ModelState.IsValid FALSE RRS feed

  • Question

  • User1991482975 posted

    Hi,

    i have the following imput type="file" which works great :

                            <div class="row photo-div-file" style="background-color:#ffffff;">
                                <div class="col-sm-12 col-md-12">
                                    <p>
                                        <label for="file1" class="photo-label-file">
                                            <b class="fa fa-cut-square-o"></b>
    
                                            <i class="fa fa-camera"></i>
    
                                            <span>@ViewRes.Shared.UploadFoto</span>
                                        </label>
                                        <input class="photo-input-file" type="file" accept="image/*" onchange="loadFile(event)" name="files" id="file1" translate="yes">
                                        <img id="output" style="max-width:200px;" />
                                    </p>
    
                                </div>
                            </div>

    this is my controller

    [ValidateAntiForgeryToken]
            public ActionResult AdvertisingUpload([Bind(Include = "PartnerAdvertiseId,PartnerId,PartnerAdvertiseTitle")] PartnerAdvertise partneradvertise, IEnumerable<HttpPostedFileBase> files)
            {
    foreach (var file in files)
                    {
    
                        if (file != null)
                        {
    
                            if (file.ContentLength > 0)
                            {
    
                                var sizeMb = (file.ContentLength / 1024f) / 1024f; //file.contentlength is in bytes
    
                                var todaydate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                var todaydatefriendly = todaydate.ImageFriendly();
                                var myuploadiwthoutextension = Path.GetFileNameWithoutExtension(file.FileName);
                                var myuploadextension = Path.GetExtension(file.FileName);
                                var myuploadiwthoutextensionfriendly = myuploadiwthoutextension.ImageFriendly();
                                var myuploadpartneradvertisetitlefriendly = partneradvertise.PartnerAdvertiseTitle.ImageFriendly();
    
                                var fileName = todaydatefriendly + "-" + myuploadiwthoutextensionfriendly + myuploadpartneradvertisetitlefriendly + myuploadextension;
                                var path = Path.Combine(Server.MapPath("~/Content/PartnerAdvertise"), fileName);
    
                                var fileName200 = todaydatefriendly + "-" + myuploadiwthoutextensionfriendly + myuploadpartneradvertisetitlefriendly + "-200" + myuploadextension;
                                var path200 = Path.Combine(Server.MapPath("~/Content/PartnerAdvertise"), fileName200);
    
                                var fileName750 = todaydatefriendly + "-" + myuploadiwthoutextensionfriendly + myuploadpartneradvertisetitlefriendly + "-750" + myuploadextension;
                                var path750 = Path.Combine(Server.MapPath("~/Content/PartnerAdvertise"), fileName750);
    
                                file.SaveAs(path);
    
                                WebImage img = new WebImage(path);

    the problem is when i send my form o would love to get back my file, but each time i have ModelState notvalid i got back to my form and i lose the image...

    how to get back my image in my form?

    thansk

    Friday, December 4, 2020 9:34 AM

Answers

  • User1686398519 posted

    Hi grafic.web, 

    The way to set file input values ​​for security reasons is that the user selects the file.

    The problem now is that when you find the value of ModelState.IsValid is false after submitting the form to the backend, you need to return to the page and still retain the value of the file input.

    You can use the client side validation in ASP.NET MVC, the form will only be submitted after all models are correctly validated, so that the selected files are preserved.

    1. You need to reference these two files: jquery.validate.min.js, jquery.validate.unobtrusive.min.js.
    2. You can click this link to learn how to enable client side validation in ASP.NET MVC.

    View

    @{
    ViewBag.Title = "Index"; Layout = null; } <h2>Index</h2> @model DailyMVCDemo.Models.TestDataModel @using (Html.BeginForm("TestPost", "Test8", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.DisplayNameFor(m => m.Id) @Html.TextBoxFor(m => m.Id) @Html.ValidationMessageFor(m => m.Id) @Html.DisplayNameFor(m => m.Name) @Html.TextBoxFor(m => m.Name) @Html.ValidationMessageFor(m => m.Name) <input class="photo-input-file" type="file" accept="image/*" name="files" id="file1" translate="yes"> <button>submit</button> } <script src="~/Scripts/jquery-3.4.1.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 10, 2020 6:52 AM

All replies

  • User475983607 posted

    You must have added validation to a model property and the validation caught the error.  Can you share the model. the actual error, and where you are validating the model?   

    grafic.web

    how to get back my image in my form?

    I'm not sure what you mean by "get back"  I assume you wish to see the image in the browser?  Just pass the image path to the View, ViewBag is a good option, and set the img src attribute.  This is very straightforward MVC programming and HTML.

    <img src="@ViewBag.MyImagePath" />

    https://www.w3schools.com/tags/tag_img.asp

    I seems like you did not share the actual code causing the problem.  The code you did share is rather confusing.

    Friday, December 4, 2020 11:31 AM
  • User1991482975 posted

    hi,

    i am talking about the upload field

    <input type="file" 

    and not the img field..

    i need to repopulate this field when the form goes back to my view page because of model invalid

    when the form is reloaded the image just choosen disappear

    i need to get back that image

    how to achive this?

    Friday, December 4, 2020 12:14 PM
  • User475983607 posted

    i need to repopulate this field when the form goes back to my view page because of model invalid

    Browser security does not allow a web server to select a file on the user's system.  The use must always select the file. 

    Perhaps implement client side validation rather than only server side validation.

    Friday, December 4, 2020 12:55 PM
  • User1991482975 posted

    yes it is possible..

    i am waiting for the right answer..

    anyone knows how to achive this?

    Friday, December 4, 2020 12:57 PM
  • User475983607 posted

    grafic.web

    yes it is possible..

    i am waiting for the right answer..

    If I understand the requirement, you do not want to force the user to select a file upload if there is a model validation error on the server.  This is NOT possible due to browser security.  Web applications could upload any file from the user's machine if this were possible.

    https://www.google.com/search?q=pre+populate+file+upload+field

    Use standard client side validation to stop the post if there are any validation errors.   The user can fix the error and submit the form without having to re-select the file.

    If I do not understand the requirement, then clearly explain what you are trying to do.

    Friday, December 4, 2020 1:44 PM
  • User-474980206 posted

    If you do server validation of a form post with a file, and you don’t want the user to have to reupload the file, then you code for that. On post back if the file is valid, save it on the server. If the form is invalid display error and render message file uploaded, but give option to replace. 

    Friday, December 4, 2020 3:36 PM
  • User1991482975 posted

    Hi Bruce,

    any code for thid?

    thanks

    Saturday, December 5, 2020 12:34 PM
  • User1686398519 posted

    Hi grafic.web, 

    The way to set file input values ​​for security reasons is that the user selects the file.

    The problem now is that when you find the value of ModelState.IsValid is false after submitting the form to the backend, you need to return to the page and still retain the value of the file input.

    You can use the client side validation in ASP.NET MVC, the form will only be submitted after all models are correctly validated, so that the selected files are preserved.

    1. You need to reference these two files: jquery.validate.min.js, jquery.validate.unobtrusive.min.js.
    2. You can click this link to learn how to enable client side validation in ASP.NET MVC.

    View

    @{
    ViewBag.Title = "Index"; Layout = null; } <h2>Index</h2> @model DailyMVCDemo.Models.TestDataModel @using (Html.BeginForm("TestPost", "Test8", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.DisplayNameFor(m => m.Id) @Html.TextBoxFor(m => m.Id) @Html.ValidationMessageFor(m => m.Id) @Html.DisplayNameFor(m => m.Name) @Html.TextBoxFor(m => m.Name) @Html.ValidationMessageFor(m => m.Name) <input class="photo-input-file" type="file" accept="image/*" name="files" id="file1" translate="yes"> <button>submit</button> } <script src="~/Scripts/jquery-3.4.1.min.js"></script> <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

    Best Regards,

    YihuiSun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 10, 2020 6:52 AM