public ActionResult Create([Bind(Include = "MessageId,Title,Body,Date,TopicId,MemberId")] MessageViewModel messageVm, int? CurrentTopics, int? CurrentUsers) { if (ModelState.IsValid) { // Check if the topic is new, if so create and save a new topic to the database before adding the TopicId to the new message Topic topic = (from t in db.Topics where t.TopicId == CurrentTopics select t).FirstOrDefault(); if (topic == null) { topic = new Topic() { Title = messageVm.Subject.Title }; db.Topics.Add(topic); db.SaveChanges(); } // Using the MessageViewModel input, create a message object Message message = new Message() { Body = messageVm.Body, Date = DateTime.Now, MemberId = (int)CurrentUsers, // Cast possibly null int, app will still crash if it is not filled when form is submitted. TODO: modify when Member is stored in session TopicId = topic.TopicId }; // Add and save Message to db db.Messages.Add(message); db.SaveChanges(); // Redirect user to the forum topic which they just added a message to return RedirectToAction("Details", "Topics", new { id = topic.TopicId }); } // If form is not completed properly, repopulate the dropdownlist for members and topics ViewBag.CurrentUsers = new SelectList(db.Members.OrderBy(m => m.UserName), "MemberId", "UserName"); ViewBag.CurrentTopics = new SelectList(db.Topics.OrderBy(s => s.Title), "TopicId", "Title"); return View(messageVm); }
public ActionResult Create([Bind(Include = "MessageId,Body,Date,Subject,User")] MessageViewModel messageVm, int? CurrentUsers) { // Verify form has appropriate data and that a user has been marked if (ModelState.IsValid && CurrentUsers != null) { // Add new Topic to db, then create a message under that topic Topic topic = new Topic() { Title = messageVm.Subject.Title }; db.Topics.Add(topic); db.SaveChanges(); Message message = new Message() { Body = messageVm.Body, Date = DateTime.Now, MemberId = (int)CurrentUsers, TopicId = topic.TopicId }; db.Messages.Add(message); db.SaveChanges(); return RedirectToAction("Index"); } // If form is invalid repopulate form with sent data, also repopulate the user dropdownlist ViewBag.CurrentUsers = new SelectList(db.Members.OrderBy(m => m.UserName), "MemberId", "UserName"); return View(messageVm); }