Question

I'm getting some exceptions when sending form with empty fields to controller. Actually I'm not using typed view I just create a form that send data to controller through @Html.BeginForm. When I don't enter "dateParution" I'm getting an ArgumentException which says that dateParution can not get null value , and when I don't enter file I'm getting an NullReferenceException. What I want is to show user a message to tell that all fields should be entered and avoid the exception page.

Here is my view:

@using (Html.BeginForm("Form", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
               {     
<table cellpadding="2" cellspacing="10">
                            <tr>
                                <td>
                                    Choisir journal :
                                </td>
                                <td>
                                    @Html.DropDownList("IdJournal")
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Numéro de l'édition:
                                </td>
                                <td>
                                    <input type="text" name="numEditionJournal" />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    Date de parution:
                                </td>
                                <td>
                                    <input class="form-control span2" name="dateParution" size="16" type="date" value="12-02-2014" >
                                    </td>
                            </tr>
                            <tr>
                                <td>
                                    Choisirr image:
                                </td>
                                <td>
                                    <input type="file" multiple name="files" id="upload"/>
                                </td>
                            </tr>
                        </table>


                </div>


                     <button type="submit" id="load" class="btn btn-primary">Confirmer</button>

               }

and my controller

[HttpPost]
    public ActionResult Form(List<HttpPostedFileBase> files, DateTime dateParution, long IdJournal, string numEditionJournal)
    {


        ScanITAPP.Service.ImageRender service = new Service.ImageRender();
        /* service.UploadImageToDB(file, dateParution, IdJournal, numEditionJournal);*/
        try
        {
            if (files != null && dateParution != null && numEditionJournal != null)
            {
                foreach (HttpPostedFileBase file in files)
                {

                    byte[] data;
                    using (Stream inputStream = file.InputStream)
                    {
                        MemoryStream memoryStream = inputStream as MemoryStream;
                        if (memoryStream == null)
                        {
                            memoryStream = new MemoryStream();
                            inputStream.CopyTo(memoryStream);
                        }
                        data = memoryStream.ToArray();
                    }

                    string extension = System.IO.Path.GetExtension(file.FileName);
                    string filename = System.IO.Path.GetFileNameWithoutExtension(file.FileName);

                    if (extension == ".pdf")
                    {

                        using (var image = new MagickImage())
                        {
                            image.Quality = 300;
                            image.Density = new MagickGeometry(144, 144);
                            image.Read(data);


                            image.Write("C:\\AnnoncesImages\\" + filename + ".jpg");
                            byte[] bytes = System.IO.File.ReadAllBytes("C:\\AnnoncesImages\\" + filename + ".jpg");

                            AnnonceVImgSet annImg = new AnnonceVImgSet();
                            annImg.Id = 1;

                            ImgOrgSet img = new ImgOrgSet();

                            img.User_Id = 1;
                            img.Journal_Id = IdJournal;
                            img.dateModif = DateTime.Now;
                            img.dateParution = dateParution;
                            img.dateSaisi = DateTime.Now;
                            img.numEditionJournal = numEditionJournal;

                            img.image = bytes;
                            using (Bd_scanitEntities dbContext = new Bd_scanitEntities())
                            {
                                dbContext.ImgOrgSet.Add(img);
                                dbContext.SaveChanges();
                            }
                            TempData["Message"] = "Image PDF ajoutée ";
                        }
                    }
                    else
                    {
                        service.UploadImageToDB(file, dateParution, IdJournal, numEditionJournal);
                        TempData["Message"] = "Image ajoutée ";
                    }
                }
                return RedirectToAction("Index");
            }
            else
            {
                ViewBag.RenderedAlert = "Vous n'avez pas rempli tous les champs";
                TempData["Message"] = "Image non ajoutée if";
            }



        }
        catch (ArgumentException)
        {
            ViewBag.RenderedAlert = "Vous n'avez pas rempli tous les champs";
            TempData["Message"] = "Image ajoutée catch";
            return View("Index");
        }
        return View("Index");
    }
Was it helpful?

Solution

The issue is here:

public ActionResult Form(List<HttpPostedFileBase> files, DateTime dateParution, long IdJournal, string numEditionJournal)

If the modelbinder cannot find a DateTime and long by their respective names, it will pass null. Since these types are non-nullable types, that function cannot be called (as the needed parameters are not present). List<> and string are not problematic, as they can inherently be null.

Solution: make the other types nullable (notice the added ? characters):

public ActionResult Form(List<HttpPostedFileBase> files, DateTime? dateParution, long? IdJournal, string numEditionJournal)

Note that using Nullable<long> or long? is equivalent. The same goes for any other type :)

Edit - Update

However, if these fields are required for you (it shouldn't ever be null to work correctly), you should look into client-side validation. There are many plugins to help you with this; and if you want to avoid dependencies, it's not that hard to do on your own.

At the very core, your webpage has to check if those form fields are entered correctly. If they are not, your webpage should not submit the form, but relay an error message to the user.

OTHER TIPS

Looks like you're passing NULL value for dateParution parameter which is of DateTime type and won't allow NULL values.

Use jquery validation plug in to do client side validations.

http://jqueryvalidation.org/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top