Question

I want to add posts to threads in my forum project, but to do so I need to pass a parameter with thread ID, so after creating post it will redirect me back to that specific thread, but the problem is that I have no idea how to pass that parameter...

Here is my Create() code:

// GET: /Posts/Create   
public ActionResult Create(int id)
{
    ViewBag.ThreadId = new SelectList(db.Albums, "ThreadId", "Title");
    ViewBag.IdOfThread = id;
    return View();
}

//
// POST: /Posts/Create    
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Posts posts)
{
    if (ModelState.IsValid)
    {
        db.Posts.Add(posts);
        db.SaveChanges();
        return RedirectToAction("Index", new { **id = 5** });
    }

    ViewBag.ThreadId = new SelectList(db.Albums, "ThreadId", "Title", posts.ThreadId);
    //ViewBag.IdOfThread = id;
    return View(posts);
}

When I strongly type number id = 5 it works as intended, so how can I make ActionResult Create(Posts posts) see my ViewBoxes from Create View? Or maybe there is some better way to do that without using ViewBoxes?

Était-ce utile?

La solution

Through the glory of EF when you add a model to the Entity and call SaveChanges() it will automatically put the ID back into the model.

    if (ModelState.IsValid)
    {
        db.Posts.Add(posts);
        db.SaveChanges();

        // Replace Id with whatever your auto increment PK is.
        return RedirectToAction("Index", new { id = posts.Id }); 
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top