Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8635725
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T10:02:56+00:00 2026-06-12T10:02:56+00:00

I have this two objects – Magazine and Author (M-M relationship): public partial class

  • 0

I have this two objects – Magazine and Author (M-M relationship):

public partial class MAGAZINE
    {
        public MAGAZINE()
        {
            this.AUTHORs = new HashSet<AUTHOR>();
        }

        public long REF_ID { get; set; }
        public string NOTES { get; set; }
        public string TITLE { get; set; }

        public virtual REFERENCE REFERENCE { get; set; }
        public virtual ICollection<AUTHOR> AUTHORs { get; set; }
    }

public partial class AUTHOR
{
    public AUTHOR()
    {  
         this.MAGAZINEs = new HashSet<MAGAZINE>();
    }

            public long AUTHOR_ID { get; set; }
            public string FULL_NAME { get; set; }

            public virtual ICollection<MAGAZINE> MAGAZINEs { get; set; }
        }
}

My problem is that I can’t seem to update the number of authors against a magazine e.g. if I have 1 author called “Smith, P.” stored already against a magazine, I can add another called “Jones, D.”, but after the post back to the Edit controller the number of authors still shows 1 – i.e. “Smith, P.H”.

Please not that I have successfully model bound the number of authors back to the parent entity (Magazine), it uses a custom model binder to retrieve the authors and bind to the Magazine (I think), but it still doesn’t seem to update properly.

My code for updating the model is straight forward – and shows the variable values both before and after:

public ActionResult Edit(long id)
    {
        MAGAZINE magazine = db.MAGAZINEs.Find(id);
        return View(magazine);
    }

and here are the variables pre-editing/updating –

enter image description here

[HttpPost]
public ActionResult Edit(MAGAZINE magazine)
   {
       if (ModelState.IsValid)
       {
           db.Entry(magazine).State = EntityState.Modified;
           db.SaveChanges();
           return RedirectToAction("Index");
       }

       return View(magazine);
   }

…and here are the variables after a new author has been added…

I am getting suspicious that the author entity is showing, post edit that it is not bound to any magazine and I am guessing this is why it is not being updated back to the magazine entity – but it is perplexing as I am effectively dealing with the same magazine entity – I guess it may be something to do with the custom model binder for the author.

Can anyone help on this matter?

For completeness – I have included my AuthorModelBinder class too –

public class AuthorModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            if (values != null)
            {
                // We have specified asterisk (*) as a token delimiter. So
                // the ids will be separated by *. For example "2*3*5"
                var ids = values.AttemptedValue.Split('*');

                List<int> validIds = new List<int>();
                foreach (string id in ids)
                {
                    int successInt;
                    if (int.TryParse(id, out successInt))
                    {
                        validIds.Add(successInt);
                    }
                    else
                    {
                        //Make a new author
                        AUTHOR author = new AUTHOR();
                        author.FULL_NAME = id.Replace("\'", "").Trim();
                        using (RefmanEntities db = new RefmanEntities())
                        {
                            db.AUTHORs.Add(author);
                            db.SaveChanges();
                            validIds.Add((int)author.AUTHOR_ID);
                        }
                    }
                }

                 //Now that we have the selected ids we could fetch the corresponding
                 //authors from our datasource
                var authors = AuthorController.GetAllAuthors().Where(x => validIds.Contains((int)x.Key)).Select(x => new AUTHOR
                {
                    AUTHOR_ID = x.Key,
                    FULL_NAME = x.Value
                }).ToList();
                return authors;
            }
            return Enumerable.Empty<AUTHOR>();
        }
    }

enter image description here

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T10:02:57+00:00Added an answer on June 12, 2026 at 10:02 am

    I faced a very similar scenario when I developed my blog using MVC/Nhibernate and the entities are Post and Tag.

    I too had an edit action something like this,

    public ActionResult Edit(Post post)
    {
      if (ModelState.IsValid)
      {
           repo.EditPost(post);
           ...
      }
      ...
    }
    

    But unlike you I’ve created a custom model binder for the Post not Tag. In the custom PostModelBinder I’m doing pretty much samething what you are doing there (but I’m not creating new Tags as you are doing for Authors). Basically I created a new Post instance populating all it’s properties from the POSTed form and getting all the Tags for the ids from the database. Note that, I only fetched the Tags from the database not the Post.

    I may suggest you to create a ModelBinder for the Magazine and check it out. Also it’s better to use repository pattern instead of directly making the calls from controllers.

    UPDATE:

    Here is the complete source code of the Post model binder

    namespace PrideParrot.Web.Controllers.ModelBinders
    {
      [ValidateInput(false)]
      public class PostBinder : IModelBinder
      {
        private IRepository repo;
    
        public PostBinder(IRepository repo)
        {
          this.repo = repo;
        }
    
        #region IModelBinder Members
    
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
          HttpRequestBase request = controllerContext.HttpContext.Request;
    
          // retrieving the posted values.
          string oper = request.Form.Get("oper"),
                   idStr = request.Form.Get("Id"),
                   heading = request.Form.Get("Heading"),
                   description = request.Form.Get("Description"),
                   tagsStr = request.Form.Get("Tags"),
                   postTypeIdStr = request.Form.Get("PostType"),
                   postedDateStr = request.Form.Get("PostedDate"),
                   isPublishedStr = request.Form.Get("Published"),
                   fileName = request.Form.Get("FileName"),
                   serialNoStr = request.Form.Get("SerialNo"),
                   metaTags = request.Form.Get("MetaTags"),
                   metaDescription = request.Form.Get("MetaDescription"),
                   themeIdStr = request.Form.Get("Theme");
    
          // initializing to default values.
          int id = 0, serialNo = 0;
          DateTime postedDate = DateTime.UtcNow;
          DateTime? modifiedDate = DateTime.UtcNow;
          postedDate.AddMilliseconds(-postedDate.Millisecond);
          modifiedDate.Value.AddMilliseconds(-modifiedDate.Value.Millisecond);
    
          /*if operation is not specified throw exception. 
            operation should be either'add' or 'edit'*/
          if (string.IsNullOrEmpty(oper))
            throw new Exception("Operation not specified");
    
          // if there is no 'id' in edit operation add error to model.
          if (string.IsNullOrEmpty(idStr) || idStr.Equals("_empty"))
          {
            if (oper.Equals("edit"))
              bindingContext.ModelState.AddModelError("Id", "Id is empty");
          }
          else
            id = int.Parse(idStr);
    
          // check if heading is not empty.
          if (string.IsNullOrEmpty(heading))
            bindingContext.ModelState.AddModelError("Heading", "Heading: Field is required");
          else if (heading.Length > 500)
            bindingContext.ModelState.AddModelError("HeadingLength", "Heading: Length should not be greater than 500 characters");
    
          // check if description is not empty.
          if (string.IsNullOrEmpty(description))
            bindingContext.ModelState.AddModelError("Description", "Description: Field is required");
    
          // check if tags is not empty.
          if (string.IsNullOrEmpty(metaTags))
            bindingContext.ModelState.AddModelError("Tags", "Tags: Field is required");
          else if (metaTags.Length > 500)
            bindingContext.ModelState.AddModelError("TagsLength", "Tags: Length should not be greater than 500 characters");
    
          // check if metadescription is not empty.
          if (string.IsNullOrEmpty(metaTags))
            bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Field is required");
          else if (metaTags.Length > 500)
            bindingContext.ModelState.AddModelError("MetaDescription", "Meta Description: Length should not be greater than 500 characters");
    
          // check if file name is not empty.
          if (string.IsNullOrEmpty(fileName))
            bindingContext.ModelState.AddModelError("FileName", "File Name: Field is required");
          else if (fileName.Length > 50)
            bindingContext.ModelState.AddModelError("FileNameLength", "FileName: Length should not be greater than 50 characters");
    
          bool isPublished = !string.IsNullOrEmpty(isPublishedStr) ? Convert.ToBoolean(isPublishedStr.ToString()) : false;
    
          //** TAGS
          var tags = new List<PostTag>();
          var tagIds = tagsStr.Split(',');
          foreach (var tagId in tagIds)
          {
            tags.Add(repo.PostTag(int.Parse(tagId)));
          }
          if(tags.Count == 0)
            bindingContext.ModelState.AddModelError("Tags", "Tags: The Post should have atleast one tag");
    
          // retrieving the post type from repository.
          int postTypeId = !string.IsNullOrEmpty(postTypeIdStr) ? int.Parse(postTypeIdStr) : 0;
          var postType = repo.PostType(postTypeId);
          if (postType == null)
            bindingContext.ModelState.AddModelError("PostType", "Post Type is null");
    
          Theme theme = null;
          if (!string.IsNullOrEmpty(themeIdStr))
            theme = repo.Theme(int.Parse(themeIdStr));
    
          // serial no
          if (oper.Equals("edit"))
          {
            if (string.IsNullOrEmpty(serialNoStr))
              bindingContext.ModelState.AddModelError("SerialNo", "Serial No is empty");
            else
              serialNo = int.Parse(serialNoStr);
          }
          else
          {
            serialNo = repo.TotalPosts(false) + 1;
          }
    
          // check if commented date is not empty in edit.
          if (string.IsNullOrEmpty(postedDateStr))
          {
            if (oper.Equals("edit"))
              bindingContext.ModelState.AddModelError("PostedDate", "Posted Date is empty");
          }
          else
            postedDate = Convert.ToDateTime(postedDateStr.ToString());
    
          // CREATE NEW POST INSTANCE
          return new Post
          {
            Id = id,
            Heading = heading,
            Description = description,
            MetaTags = metaTags,
            MetaDescription = metaDescription,
            Tags = tags,
            PostType = postType,
            PostedDate = postedDate,
            ModifiedDate = oper.Equals("edit") ? modifiedDate : null,
            Published = isPublished,
            FileName = fileName,
            SerialNo = serialNo,
            Theme = theme
          };
        }
    
        #endregion
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two objects as follows public class MyObject1 implements Serializable { private Long
I have this two objects class RNB { public RNB(double roomRate, double roomDays) {
Using Dozer to map two objects, I have: /** /* This first class uses
Still having trouble with this language. Ok, let's say I have two objects. The
I have two objects of Zend_Date class and I want to calculate the difference
I have two objects Person(long id, String name, PersonInfo info) and PersonInfo(long id, String
I'm using CoreData and I have two managed objects: Author and Book. An author
I have two objects and I dont want to create a wrapper class to
Suppose I have a design like this: Object GUI has two objects: object aManager
I have two Entity Framework objects with a one-to-many relationship: widget(parent) and widgetNail(child) Widget

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.