LiamB
LiamB

Reputation: 18606

Asp.Net MVC View: Create and Relationship tables

I have a message board in ASP.Net MVC and when the user creates a new Post they must select a category, when I create a view (Create) the field (Categories) doesnt appear?

The database has a middle table MessageToCatRel which contains a messageID and a CatId. I think this is what is confusing MVC. At the moment i am doing the following, but dont like the idea of using the Request.Form. How can I get it to post back in the Object like the other fields?

  public ActionResult Create(Message messageToCreate) //Post back from Message Post
            {
                if (!ModelState.IsValid)
                {
                    this.LoadCategoryViewData();
                    return View();
                }

                //Now try and save this in the Database     /

/And Save
                IMessageRepository repo = new MessageRepository();
                MessageCategory curCatRel = new MessageCategory();
                curCatRel.CategoryID = Convert.ToInt32(Request.Form["Categories"]);

                messageToCreate.MessageCategories.Add(curCatRel);
                messageToCreate.CreatedBy = 1; //Temp messure
                messageToCreate.PublishDateTime = DateTime.Now;

                repo.AddMessage(messageToCreate);
                repo.Save();

Upvotes: 0

Views: 334

Answers (2)

LiamB
LiamB

Reputation: 18606

Thanks for the reply, doesnt really do what I wanted. I'm sticking to use ViewData for a bit.

Thanks

Upvotes: 0

Arnis Lapsa
Arnis Lapsa

Reputation: 47677

Change

public ActionResult Create(Message messageToCreate)

to

public ActionResult Create(Message messageToCreate, int Categories)

Is that's what you are looking for?

Maybe this?

public ActionResult Create(Message messageToCreate, MessageCategory category)

and this in markup:

<form ..> <input type='hidden' name='MessageCtaegory.CategoryID'>1</input></form>

Upvotes: 1

Related Questions