locked
how to get and show error message from controller to view RRS feed

  • Question

  • User10778361 posted

    like the code:

    View:

    <body>
    
        @using (Html.BeginForm("ImageToPDF_Index", "ImageToPDF", FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            <input type="file" id="postedFile" name="postedFile" multiple />
            <input type="submit" id="btnSubmit" value="Upload" />
    
            <div class="create-button">
                <button id="btnSubmit" onclick="doSubmit()" type="button" class="col align-self-center btn btn-primary" />submit
                @*<button id="btnCancel" onclick="goBack()" class="col-md-auto btn btn-primary">cancel</button>*@
            </div>
        }
    
            <div id="errorid" class="has-error">
                //here show the error files name
            </div>
    </body>
    
    
    
    @section scripts{
        <script>
    
            function doSubmit() {
                var form_data = new FormData($("form")[0]);
    
                $.ajax({
                    type: "post",
                    url: "@Url.Action("Index2", "ImageToPDF")",
                    cache: false,
                    contentType: false, 
                    processData: false,
                    data: form_data,
                    dataType: "json",
                    //error: function () {
                    //    alert("fail");
                    //},
                    success: function (response) {
                        if (response.success == 0) {
                            alert(response);
                        }
                        else {
                            $("#errorid").append("<div>filname:" + response.filename+" "+response.msg+"</div >");
                        }
                        $("#inputdata").removeClass("notclick");
                        $("#btnstart").removeAttr("disabled");
                    }
    
                });
            }
        </script>
    }

    controller:

    public ActionResult ImageToPDF_Index()
            {
                return View();
            }
     [HttpPost]
            [ValidateInput(false)]
            public JsonResult Index2(IEnumerable<HttpPostedFileBase> postedFile)
            {
    
                List<string> errorfiles = new List<string>();
                var flag = 0;
                string errormassage = "";
    
    
                try
                {
    ...here handle postedFile files
    }
    catch (Exception e)
                {
                    flag = 1;
                    errormassage = e.Message;
                    errorfiles.Add("error filename is:xxx");//If there is an exception in the processed file, how to record this file and display it on the View
                }
    
                if (flag == 0)
                {
                    // return Json("success", JsonRequestBehavior.AllowGet);
                    return Json(new { success = flag, msg = "success" }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { success = flag, msg = errormassage ,filename= errorfilename }, JsonRequestBehavior.AllowGet);
    
                }
            }

    If there are other ways to achieve the same purpose, it is also very welcome.

    Thanks.

    Sunday, May 17, 2020 11:43 PM

Answers

  • User634495354 posted

    Hi ,ttprettycoder

    From your code,I think you want to realize a function that can upload multiple files and show success or error, but there are some problems in your code.

    Actually, if you want to post data by beginform,beginform can't receive data from controller and show result.,even though writing ajax.Ajax will not work in beginform, that is why the "submit" button doesn't work but "upload" button can click and  post data.

    If you want to post data by ajax without beginform, the controller will not get the instance of object.

    To realize the function, I recommend using "ViewBag" ,here's the result.

    View

    <body>
    
            @using (Html.BeginForm("Index2", "ImageToPDF", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
            }
                <input type="file" id="postedFile" name="postedFile" multiple />
                <input type="submit" id="btnSubmit" value="Upload" />
    
                <div class="create-button">
                    <button id="btnSubmit" onclick="doSubmit()" type="button" class="col align-self-center btn btn-primary" />submit
                    @*<button id="btnCancel" onclick="goBack()" class="col-md-auto btn btn-primary">cancel</button>*@
                </div>
    
                <ul>
                    @if (ViewBag.result != null)
                    {
                        foreach (var result in ViewBag.result)
                        {
                            <li>@result</li>
                        }
    
                    }
                </ul>
            @*
            <div id="errorid" class="has-error">
                 //here show the error files name
            </div>*@
        </body>
    

    I removed your js and used Viewbag to show result about uploading.

    Controller

    public ActionResult ImageToPDF_Index()
            {
                return View();
            }
    
            [HttpPost]
            [ValidateInput(false)]
            public ActionResult Index2(IEnumerable<HttpPostedFileBase> postedFile)
            {
    
                 //List<string> errorfiles = new List<string>();
                   List<string> results = new List<string>(); //it used to store every result of file
                  //var flag = 0;
                   string errormassage = "";
                   foreach (var postfile in postedFile) 
                   {
                       string filename = postfile.FileName;  //get the name of file you upload
                       string fileExtension = Path.GetExtension(filename); //File extension,it is unnecessary,you can delete it if you wany
    
                    try
                       {
                           string filePath = Server.MapPath("~/Uploads"); //This is the directory to which you want to upload the file                       if (!Directory.Exists(filePath))
                        {
                               Directory.CreateDirectory(filePath);//create the directory
                           }
                           postfile.SaveAs(Path.Combine(filePath, filename));
                        results.Add(filename+"-success"); //upload success
                       }
                       catch (Exception e)
                       {
                         //  flag = 1;
                           errormassage = e.Message;
                          // errorfiles.Add(filename);//If there is an exception in the processed file, how to record this file and display it on the View
                        results.Add(filename + "errormassage");
                    }
                   }
                    ViewBag.result = results;   //all result of files
                    return View("ImageToPDF_Index");
            }
    

    Viewbag will transfer the result of every file.

    I have tested it to upload many images at once and success.

    Best regards.

    Bruce12138

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 19, 2020 3:00 AM

All replies

  • User634495354 posted

    Hi , ttprettycoder

    From your code, I think you want to realize a function that can upload multiple files and show success or error, but there are some problems in your code.

    Actually, if you want to post data by beginform, beginform can't receive data form controller and show result. even though writing ajax. Ajax will not work in beginform, that is why the "submit" button doesn't work but "upload" button can click and post data.

    If you want to post data by ajax without beginform, the controller will not get the instance of object.

    To realize the function, I recommend using "ViewBag". Here‘s the code.

    Your view:

    <body>
    
            @using (Html.BeginForm("Index2", "ImageToPDF", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                <input type="file" id="postedFile" name="postedFile" multiple />
                <input type="submit" id="btnSubmit" value="Upload" />
    
                <div class="create-button">
                    <button id="btnSubmit" onclick="doSubmit()" type="button" class="col align-self-center btn btn-primary" />submit
                    @*<button id="btnCancel" onclick="goBack()" class="col-md-auto btn btn-primary">cancel</button>*@
                </div>
    
                <ul>
                    @if (ViewBag.result != null)
                    {
                        foreach (var result in ViewBag.result)
                        {
                            <li>@result</li>
                        }
    
                    }
                </ul>
            }
            @*
            <div id="errorid" class="has-error">
                 //here show the error files name
            </div>*@
        </body>
    

    I removed your js and used Viewbag to show result about uploading.

    Your controller:

    public ActionResult ImageToPDF_Index()
            {
                return View();
            }
    
            [HttpPost]
            [ValidateInput(false)]
            public ActionResult Index2(IEnumerable<HttpPostedFileBase> postedFile)
            {
    
                 //List<string> errorfiles = new List<string>();
                   List<string> results = new List<string>(); //it used to store every result of file
                  //var flag = 0;
                   string errormassage = "";
                   foreach (var postfile in postedFile) 
                   {
                       string filename = postfile.FileName;  //get the name of file you upload
                       string fileExtension = Path.GetExtension(filename); //File extension,it is unnecessary,you can delete it if you wany
    
                    try
                       {
                           string filePath = Server.MapPath("~/Uploads"); //This is the directory to which you want to upload the file                       if (!Directory.Exists(filePath))
                        {
                               Directory.CreateDirectory(filePath);//create the directory
                           }
                           postfile.SaveAs(Path.Combine(filePath, filename));
                        results.Add(filename+"-success"); //upload success
                       }
                       catch (Exception e)
                       {
                         //  flag = 1;
                           errormassage = e.Message;
                          // errorfiles.Add(filename);//If there is an exception in the processed file, how to record this file and display it on the View
                        results.Add(filename + "errormassage");
                    }
                   }
                    ViewBag.result = results;   //all result of files
                    return View("ImageToPDF_Index");
            }
    

    Viewbag will transfer the result of every file.

    I have tested it to upload many images at once and success.

    Best regards.

    Bruce12138

    Tuesday, May 19, 2020 2:39 AM
  • User634495354 posted

    Hi ,ttprettycoder

    From your code,I think you want to realize a function that can upload multiple files and show success or error, but there are some problems in your code.

    Actually, if you want to post data by beginform,beginform can't receive data from controller and show result.,even though writing ajax.Ajax will not work in beginform, that is why the "submit" button doesn't work but "upload" button can click and  post data.

    If you want to post data by ajax without beginform, the controller will not get the instance of object.

    To realize the function, I recommend using "ViewBag" ,here's the result.

    View

    <body>
    
            @using (Html.BeginForm("Index2", "ImageToPDF", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
            }
                <input type="file" id="postedFile" name="postedFile" multiple />
                <input type="submit" id="btnSubmit" value="Upload" />
    
                <div class="create-button">
                    <button id="btnSubmit" onclick="doSubmit()" type="button" class="col align-self-center btn btn-primary" />submit
                    @*<button id="btnCancel" onclick="goBack()" class="col-md-auto btn btn-primary">cancel</button>*@
                </div>
    
                <ul>
                    @if (ViewBag.result != null)
                    {
                        foreach (var result in ViewBag.result)
                        {
                            <li>@result</li>
                        }
    
                    }
                </ul>
            @*
            <div id="errorid" class="has-error">
                 //here show the error files name
            </div>*@
        </body>
    

    I removed your js and used Viewbag to show result about uploading.

    Controller

    public ActionResult ImageToPDF_Index()
            {
                return View();
            }
    
            [HttpPost]
            [ValidateInput(false)]
            public ActionResult Index2(IEnumerable<HttpPostedFileBase> postedFile)
            {
    
                 //List<string> errorfiles = new List<string>();
                   List<string> results = new List<string>(); //it used to store every result of file
                  //var flag = 0;
                   string errormassage = "";
                   foreach (var postfile in postedFile) 
                   {
                       string filename = postfile.FileName;  //get the name of file you upload
                       string fileExtension = Path.GetExtension(filename); //File extension,it is unnecessary,you can delete it if you wany
    
                    try
                       {
                           string filePath = Server.MapPath("~/Uploads"); //This is the directory to which you want to upload the file                       if (!Directory.Exists(filePath))
                        {
                               Directory.CreateDirectory(filePath);//create the directory
                           }
                           postfile.SaveAs(Path.Combine(filePath, filename));
                        results.Add(filename+"-success"); //upload success
                       }
                       catch (Exception e)
                       {
                         //  flag = 1;
                           errormassage = e.Message;
                          // errorfiles.Add(filename);//If there is an exception in the processed file, how to record this file and display it on the View
                        results.Add(filename + "errormassage");
                    }
                   }
                    ViewBag.result = results;   //all result of files
                    return View("ImageToPDF_Index");
            }
    

    Viewbag will transfer the result of every file.

    I have tested it to upload many images at once and success.

    Best regards.

    Bruce12138

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 19, 2020 3:00 AM