IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

ASP.NET MVC Discussion :

problème entre jquery validation et input type file


Sujet :

ASP.NET MVC

  1. #1
    Membre actif
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Décembre 2007
    Messages
    696
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine Maritime (Haute Normandie)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Décembre 2007
    Messages : 696
    Points : 222
    Points
    222
    Par défaut problème entre jquery validation et input type file
    Bonjour.

    J'ai besoin d'aide pour un problème lié à un input type file, dans un de mes formulaires.

    tout d'abord, voici mon fichier FileBoxHtmlHelperExtension.cs :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    using System;
    using System.Collections.Generic;
    using System.Linq.Expressions;
    using System.Web.Mvc;
    using System.Web.Routing;
     
    namespace CheckpointWeb.Models
    {
        /// <summary>
        /// Html helper extension for an Input file upload element
        /// </summary>
        public static class FileBoxHtmlHelperExtension
        {
            /// <summary>
            /// Returns a file input element by using the specified HTML helper and the name of the form field.
            /// </summary>
            /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
            /// <param name="name">The name of the form field and the <see cref="System.Web.Mvc.ViewDataDictionary" /> key that is used to look up the validation errors.</param>
            /// <returns>
            /// An input element that has its type attribute set to "file".
            /// </returns>
            public static MvcHtmlString FileBox(this HtmlHelper htmlHelper, string name)
            {
                return htmlHelper.FileBox(name, (object)null);
            }
            /// <summary>
            /// Returns a file input element by using the specified HTML helper, the name of the form field, and the HTML attributes.
            /// </summary>
            /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
            /// <param name="name">The name of the form field and the <see cref="System.Web.Mvc.ViewDataDictionary" /> key that is used to look up the validation errors.</param>
            /// <param name="htmlAttributes">An object that contains the HTML attributes for the element. The attributes are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax.</param>
            /// <returns>
            /// An input element that has its type attribute set to "file".
            /// </returns>
            public static MvcHtmlString FileBox(this HtmlHelper htmlHelper, string name, object htmlAttributes)
            {
                return htmlHelper.FileBox(name, new RouteValueDictionary(htmlAttributes));
            }
            /// <summary>
            /// Returns a file input element by using the specified HTML helper, the name of the form field, and the HTML attributes.
            /// </summary>
            /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
            /// <param name="name">The name of the form field and the <see cref="System.Web.Mvc.ViewDataDictionary" /> key that is used to look up the validation errors.</param>
            /// <param name="htmlAttributes">An object that contains the HTML attributes for the element. The attributes are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax.</param>
            /// <returns>
            /// An input element that has its type attribute set to "file".
            /// </returns>
            public static MvcHtmlString FileBox(this HtmlHelper htmlHelper, string name, IDictionary<String, Object> htmlAttributes)
            {
                var tagBuilder = new TagBuilder("input");
                tagBuilder.MergeAttributes(htmlAttributes);
                tagBuilder.MergeAttribute("type", "file", true);
                tagBuilder.MergeAttribute("name", name, true);
                tagBuilder.GenerateId(name);
     
     
                ModelState modelState;
                if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState))
                {
                    if (modelState.Errors.Count > 0)
                    {
                        tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
                    }
                }
     
     
                return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.SelfClosing));
            }
            /// <summary>
            /// Returns a file input element by using the specified HTML helper and the name of the form field as an expression.
            /// </summary>
            /// <typeparam name="TModel">The type of the model.</typeparam>
            /// <typeparam name="TValue">The type of the value.</typeparam>
            /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
            /// <param name="expression">The expression that resolves to the name of the form field and the <see cref="System.Web.Mvc.ViewDataDictionary" /> key that is used to look up the validation errors.</param>
            /// <returns>
            /// An input element that has its type attribute set to "file".
            /// </returns>
            public static MvcHtmlString FileBoxFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
            {
                return htmlHelper.FileBoxFor<TModel, TValue>(expression, (object)null);
            }
            /// <summary>
            /// Returns a file input element by using the specified HTML helper and the name of the form field as an expression.
            /// </summary>
            /// <typeparam name="TModel">The type of the model.</typeparam>
            /// <typeparam name="TValue">The type of the value.</typeparam>
            /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
            /// <param name="expression">The expression that resolves to the name of the form field and the <see cref="System.Web.Mvc.ViewDataDictionary" /> key that is used to look up the validation errors.</param>
            /// <param name="htmlAttributes">An object that contains the HTML attributes for the element. The attributes are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax.</param>
            /// <returns>
            /// An input element that has its type attribute set to "file".
            /// </returns>
            public static MvcHtmlString FileBoxFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
            {
                return htmlHelper.FileBoxFor<TModel, TValue>(expression, new RouteValueDictionary(htmlAttributes));
            }
            /// <summary>
            /// Returns a file input element by using the specified HTML helper and the name of the form field as an expression.
            /// </summary>
            /// <typeparam name="TModel">The type of the model.</typeparam>
            /// <typeparam name="TValue">The type of the value.</typeparam>
            /// <param name="htmlHelper">The HTML helper instance that this method extends.</param>
            /// <param name="expression">The expression that resolves to the name of the form field and the <see cref="System.Web.Mvc.ViewDataDictionary" /> key that is used to look up the validation errors.</param>
            /// <param name="htmlAttributes">An object that contains the HTML attributes for the element. The attributes are retrieved through reflection by examining the properties of the object. The object is typically created by using object initializer syntax.</param>
            /// <returns>
            /// An input element that has its type attribute set to "file".
            /// </returns>
            public static MvcHtmlString FileBoxFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, IDictionary<String, Object> htmlAttributes)
            {
                var name = ExpressionHelper.GetExpressionText(expression);
     
     
                return htmlHelper.FileBox(name, htmlAttributes);
            }
        }
    }
    voici mon modèle :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
     
    namespace CheckpointWeb.Models
    {
        public class AdminModelSettings
        {
            [ScaffoldColumn(false)]
            public short UserId { get; set; }
     
            [Required]
            [DataType(DataType.PostalCode)]
            [Display(Name = "Code postal")]
            [StringLength(5, MinimumLength = 5)]
            public string PostalCode { get; set; }
     
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Ville")]
            public string City { get; set; }
     
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Rue")]
            public string Street { get; set; }
     
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "RCS")]
            public string RCS { get; set; }
     
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Siret")]
            public int? Siret { get; set; }
     
            [Required]
            [DataType(DataType.Text)]
            [Display(Name = "Logo")]
            public HttpPostedFileBase Logo { get; set; }
        }
    }
    et voici ma vue :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    @model CheckpointWeb.Models.AdminModelSettings
    @using CheckpointWeb.Models;
     
    @{
        ViewBag.Title = "Paramètres";
        ViewBag.Message = "Formulaire de mise à jour de compte";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
     
    @section css {
        @Styles.Render("~/Content/css/users/CreateEdit")
    }
     
    @section jquery {
        @Scripts.Render("~/bundles/jqueryval")
    }
     
    @section js_scripts {
     
    }
     
    <hgroup class="title">
        <h1>@ViewBag.Title.</h1>
        <h2>@ViewBag.Message</h2>
    </hgroup>
     
    @using (Html.BeginForm("Settings", "Admin", FormMethod.Post, new { @class = "OrangeGradient", autocomplete = "off", enctype = "multipart/form-data" })) {
        @Html.ValidationSummary(true)
     
        <fieldset>
            <legend>@ViewBag.Title</legend>
            @Html.HiddenFor(model => model.UserId)
            <ul>
                <li>
                    @Html.LabelFor(model => model.PostalCode)
                    @Html.EditorFor(model => model.PostalCode)
                    @Html.ValidationMessageFor(model => model.PostalCode)
                </li>
                <li>
                    @Html.LabelFor(model => model.City)
                    @Html.EditorFor(model => model.City)
                    @Html.ValidationMessageFor(model => model.City)
                </li>
                <li>
                    @Html.LabelFor(model => model.Street)
                    @Html.EditorFor(model => model.Street)
                    @Html.ValidationMessageFor(model => model.Street)
                </li>
                <li>
                    @Html.LabelFor(model => model.RCS)
                    @Html.EditorFor(model => model.RCS)
                    @Html.ValidationMessageFor(model => model.RCS)
                </li>
                <li>
                    @Html.LabelFor(model => model.Siret)
                    @Html.EditorFor(model => model.Siret)
                    @Html.ValidationMessageFor(model => model.Siret)
                </li>
                <li>
                    @Html.LabelFor(model => model.Logo)
                    @Html.FileBoxFor(model => model.Logo, new { accept = "image/jpg" })
                    @Html.ValidationMessageFor(model => model.Logo)
                </li>
            </ul>
     
            <p><button type="submit">Valider</button></p>
        </fieldset>
    }
    voici le code html généré pour mon input type file :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    <input accept="image/jpg" id="Logo" name="Logo" type="file" class="input-validation-error">
    <span class="field-validation-error" data-valmsg-for="Logo" data-valmsg-replace="true"><span htmlfor="Logo" generated="true" class="" style="">Please enter a value with a valid extension.</span></span>
    J'ai malheureusement toujours le même message d'erreur lors d'un submit :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Please enter a value with a valid extension.
    Pourquoi le submit ne marche t'il pas ? O_o
    C'est un casse tête depuis 11h ce matin :/
    Pouvez-vous m'aider svp ?

  2. #2
    Membre actif
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Décembre 2007
    Messages
    696
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine Maritime (Haute Normandie)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Décembre 2007
    Messages : 696
    Points : 222
    Points
    222
    Par défaut
    Je viens de faire une petite correction dans mon modèle :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    [Required]
            [FileExtensions(Extensions="jpg")]
            [Display(Name = "Logo")]
            public HttpPostedFileBase Logo { get; set; }
    si j'utilise le TextBoxFor d'origine de asp.net, ça marche, mais toutes les extensions de fichiers apparaissent dans le browser. Même si au final je ne peux choisir que des jpg comme convenu, mais je trouve ça pas très propres. je veux forcer mon browser à filtrer les extensions dès son affichage.

    donc, ça ça ne marche pas du tout :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    @Html.FileBoxFor(model => model.Logo, new { accept = "image/jpg" })
    ça, ça marche moyen et c'est pas très propre :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    @Html.TextBoxFor(model => model.Logo, new { accept = "image/jpg", type = "file" })
    ya tout de même une évolution, qui peut m'aider à finir ?

  3. #3
    Membre actif
    Homme Profil pro
    Développeur .NET
    Inscrit en
    Décembre 2007
    Messages
    696
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine Maritime (Haute Normandie)

    Informations professionnelles :
    Activité : Développeur .NET

    Informations forums :
    Inscription : Décembre 2007
    Messages : 696
    Points : 222
    Points
    222
    Par défaut
    même la solution du TextBoxFor ne fonctionne pas en fait. Ma variable lève une exception lors de la transmission vers la méthode de mon controller.

    mon erreur :
    Le champ Logo accepte uniquement les fichiers portant les extensions suivantes : .jpg
    c'est marrant, parce que j'ai choisi un fichier jpeg >_<

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Validation formulaire ajax avec input type file
    Par lolodev dans le forum jQuery
    Réponses: 0
    Dernier message: 08/12/2011, 19h28
  2. [Conception] problème avec firefox sur les champs input type="file"
    Par maverick56 dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 9
    Dernier message: 11/05/2007, 10h57
  3. [AJAX] input type=file avec php côté serveur
    Par redstain dans le forum Général JavaScript
    Réponses: 1
    Dernier message: 04/01/2007, 15h43
  4. input type="file" problème
    Par Hayabusa dans le forum Balisage (X)HTML et validation W3C
    Réponses: 7
    Dernier message: 09/09/2006, 23h08
  5. [AJAX] Ajax avec input type file
    Par cywals dans le forum Général JavaScript
    Réponses: 8
    Dernier message: 03/08/2006, 09h29

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo