Asp – MVC: Member and Member.Items.add(Item) doesn’t get saved

asp.netasp.net-mvc

The item doesn't get saved. Only member gets saved.

When I debug [AcceptVerbs(HttpVerbs.Post)]
the information is empty in the Item. Why? How should I solve this?

When it goes to the post method of create, then the ITEM dosen't follow the member. and the ITEMS doesn't get saved. I debug the information and there are 0 Number items. Why doesn't it save Items also when I press the button.

Only the member item gets saved.

public class ClassifiedsFormViewModel
{

    IClassifiedsRepository classifiedsRepository = new ClassifiedsRepository(); 
    public Member Member { get; private set; }
    public SelectList Municipalities { get; private set; } 

    public ClassifiedsFormViewModel(Member member) 
    {   
        Member = member;
        Municipalities = new SelectList(classifiedsRepository.GetMunicipalities()
                                 ,"MunicipalityId", "Municipality1"); 
    }

}

    public ActionResult Create()
    {
        Member member = new Member();
        Item item = new Item();
        member.Items.Add(item);

        return View(new ClassifiedsFormViewModel(member));
    }

    //
    // POST: /Items/Create

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Member member)
    {

        if (ModelState.IsValid)
        {

            try
            {
                classifiedsRepository.Add(member);
                classifiedsRepository.Save();

                return RedirectToAction("Create", new { id = member.MemberId });
            }
            catch
            {
                ModelState.AddModelErrors(member.GetRuleViolations());
            }
        }

        return View(new ClassifiedsFormViewModel(member));
    }
}

Best Answer

The member which is passed into the create function is actually databound from your form. In order to ensure that it works you have to have the elements on the form named the same as the properties in your member. So if you have something called memberName in Member you would need to name the field in the view the same thing.

<form ...
  <input type="text" name="memberName"/>
... 
</form>

Edit:

After reading your comments I'm still not 100% what you're looking to do. IF you want the member you've created to have an item then move the item creation code down to the second Create. What you have passes a member with an item through to a strongly typed view. The member with the item is never persisted so it won't come back to the controller and won't make it into the model.

Related Topic