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 Discussion :

MVC Razor - Erreur SaveChanges()


Sujet :

ASP.NET

  1. #1
    Membre régulier
    Homme Profil pro
    Analyse système
    Inscrit en
    Mai 2013
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2013
    Messages : 190
    Points : 113
    Points
    113
    Par défaut MVC Razor - Erreur SaveChanges()
    Bonjour tout le monde,

    voici mon contexte :

    Controller:
    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
     
            // GET: PixelBlog/Edit/5
            public ActionResult Edit(int id)
            {
                List<SelectListItem> listSelectListItems = new List<SelectListItem>();
     
                foreach (Category cat in db.Categories)
                {
                    SelectListItem selectList = new SelectListItem()
                    {
                        Text = cat.Name,
                        Value = cat.Id.ToString()
                    };
                    listSelectListItems.Add(selectList);
                }
     
                string[] arr1 = new string[] { "NULL" };
     
                PostCategoryLink postCatViewModel = new PostCategoryLink()
                {
                    GetCategories = listSelectListItems,
                    GetCategoriesName = arr1,
                    GetPosts = db.Posts.Find(id)
                };
                return View(postCatViewModel);             
            }
     
            // POST: PixelBlog/Edit/5
            [HttpPost]
            public ActionResult Edit(PostCategoryLink postCatViewModel)
            {
                try
                {
                    // TODO: Add update logic here 
                    string s_catName;
                    if (postCatViewModel.GetCategoriesName == null)
                    {
                        s_catName = "Null";
                    }
                    else
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        sb.Append("You selected – " + string.Join(",", postCatViewModel.GetCategoriesName[0]));
                        s_catName = sb.ToString();
                    }
     
                    postCatViewModel.GetPosts.CategoryID = int.Parse(postCatViewModel.GetCategoriesName[0]);                
     
                    var context = new PixelBlogContext();
     
                    context.Entry(postCatViewModel.GetPosts).State = System.Data.Entity.EntityState.Modified;
                    context.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch (Exception e)            
                {
                    return View();
                }
            }
    Models:

    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
     
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using PixelBlog.Models;
     
    namespace PixelBlog.ViewModels
    {
        public class PostCategoryLink
        {
            public Post GetPosts { get; set; }
            public string[] GetCategoriesName { get; set; }
            public IEnumerable<SelectListItem> GetCategories { get; set; }
        }
    }
     
     
     
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Linq;
    using System.Web;
     
    namespace PixelBlog.Models
    {
        #region Post
        public class Post
        {
            /// <summary>
            /// By convention, ID is a primary key
            /// </summary>
            /// 
            public virtual int Id { get; set; }
     
            ///<summary>
            /// Title Field
            /// </summary>
            /// 
            public virtual string Title { get; set; }
     
            ///<summary>
            /// ShortDescription Field
            /// </summary>
            /// 
            public virtual string ShortDescription { get; set; }
     
            ///<summary>
            /// Description Field
            /// </summary>
            ///
            public virtual string Description { get; set; }
     
            ///<summary>
            ///Meta Field
            /// </summary>
            /// 
            public virtual string Meta { get; set; }
     
            /// <summary>
            /// UrlSlug Field
            /// </summary>
            /// 
            public virtual string UrlSlug { get; set; }
     
            /// <summary>
            /// Rate Field
            /// </summary>
            /// 
            public virtual int Rate { get; set; }
     
            /// <summary>
            /// Published Field
            /// </summary>
            /// 
            public virtual bool Published { get; set; }
     
            ///<summary>
            /// PostedOn Field
            /// </summary>
            ///
            public virtual DateTime PostedOn { get; set; }
     
            ///<summary>
            /// CategoryID Field
            /// </summary>
            /// 
            [Required]
            public int CategoryID { get; set; }
     
            ///<summary>
            /// Category FK Field
            /// </summary>
            /// 
            [ForeignKey("CategoryID")]
            public virtual Category Category { get; set; }
     
            ///<summary>
            /// TagID Field
            /// </summary>
            /// 
            [Required]
            public int TagID { get; set; }
     
            /// <summary>
            /// Tags FK Field
            /// </summary>
            /// 
            [ForeignKey("TagID")]
            public virtual Tag Tag { get; set; }
        }
        #endregion
    }
    Et 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
    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
     
    @using PixelBlog.Models
    @model PixelBlog.ViewModels.PostCategoryLink
     
    @{
        Layout = "~/Views/Shared/_Layout.cshtml";
        ViewBag.Title = "Details post";
    }
     
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
     
        <div class="form-horizontal">
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            @Html.HiddenFor(model => model.GetPosts.Id)
     
            <div class="form-group">
                @Html.LabelFor(model => model.GetPosts.Title, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.GetPosts.Title, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.GetPosts.Title, "", new { @class = "text-danger" })
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(model => model.GetPosts.ShortDescription, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.GetPosts.ShortDescription, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.GetPosts.ShortDescription, "", new { @class = "text-danger" })
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(model => model.GetPosts.Description, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.GetPosts.Description, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.GetPosts.Description, "", new { @class = "text-danger" })
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(model => model.GetPosts.Meta, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.GetPosts.Meta, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.GetPosts.Meta, "", new { @class = "text-danger" })
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(model => model.GetPosts.Rate, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.GetPosts.Rate, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.GetPosts.Rate, "", new { @class = "text-danger" })
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(model => model.GetPosts.UrlSlug, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.GetPosts.UrlSlug, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.GetPosts.UrlSlug, "", new { @class = "text-danger" })
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(model => model.GetPosts.Published, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.GetPosts.Published)
                        @Html.ValidationMessageFor(model => model.GetPosts.Published, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
     
            <div class="form-group">
                @Html.LabelFor(model => model.GetPosts.PostedOn, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.GetPosts.PostedOn, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model.GetPosts.PostedOn, "", new { @class = "text-danger" })
                </div>
            </div>
     
            @Html.DropDownListFor(m => m.GetCategoriesName, Model.GetCategories)
     
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-default" />
                </div>
            </div>
        </div>
    }
     
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    J'ai une erreur : La référence d'objet n'est pas définie à une instance d'un objet
    sur la ligne @Html.DropDownListFor(m => m.GetCategoriesName, Model.GetCategories)

    Je pense que l'erreur vient du faite que dans ma classe Post, les champs :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    [ForeignKey("CategoryID")]
            public virtual Category Category { get; set; }
     
    [ForeignKey("TagID")]
            public virtual Tag Tag { get; set; }
    sont à NULL lorsque je passe cela ici :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    context.Entry(postCatViewModel.GetPosts).State = System.Data.Entity.EntityState.Modified;
                    context.SaveChanges();
    La classe PostCategoryLink me sert à faire la liaison entre les classe Post et Category pour pouvoir afficher dans la dropdown la liste des mes catégories.

    Je pense que je me suis un peu perdu dans mon code (je débute le MVC Razor), il y a-t-il plus simple ?

    Je vous remercie pour votre aide et bon week-end !

  2. #2
    Membre régulier
    Homme Profil pro
    Analyse système
    Inscrit en
    Mai 2013
    Messages
    190
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Analyse système
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Mai 2013
    Messages : 190
    Points : 113
    Points
    113
    Par défaut
    Il y avait un conflit avec les foreign key entre mes tables (les valeurs passées étaient pas bonnes), pour cela j'ai juste rajouté pour m'aider le try catch suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
    catch (NullReferenceException e)            
                {
                    return View();
                }

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

Discussions similaires

  1. asp.net MVC Razor / AngularJS
    Par topolino dans le forum ASP.NET MVC
    Réponses: 6
    Dernier message: 10/10/2013, 21h27
  2. [MVC3 "razor"] Erreur lors de l'ajout d'un controlleur
    Par Fra212 dans le forum Entity Framework
    Réponses: 15
    Dernier message: 21/02/2012, 10h24
  3. [Asp.Net MVC 3 Razor] erreur syntax
    Par mitnick2006 dans le forum ASP.NET MVC
    Réponses: 3
    Dernier message: 21/03/2011, 12h49
  4. [ Spring MVC ] [ JBoss ] Erreur à l'instanciation..
    Par legzo dans le forum Wildfly/JBoss
    Réponses: 1
    Dernier message: 30/05/2006, 12h37

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