public ActionResult Create([Bind(Include="Id,category,postedBy,time,title,description")] Question question) { if (User.Identity.IsAuthenticated) { if (ModelState.IsValid) { question.time = DateTime.UtcNow; question.postedBy = User.Identity.GetUserId(); db.Questions.Add(question); string s = Request["tags"]; s = s.Trim(); string[] values = s.Split(','); Tag []tags = new Tag[values.Length]; QuestionTag []qt = new QuestionTag[values.Length]; //int count = 0; for (int i = 0; i < values.Length; i++) { values[i] = values[i].Trim(); string ss = values[i]; if (ss != "") { var data = db.Tags.FirstOrDefault(x => x.name.Equals(ss, StringComparison.OrdinalIgnoreCase)); tags[i] = new Tag(); if (data != null) { tags[i].Id = data.Id; } else { tags[i].name = values[i]; tags[i].time = DateTime.UtcNow; tags[i].createdBy = User.Identity.GetUserId(); db.Tags.Add(tags[i]); } } else { tags[i] = null; } } db.SaveChanges(); for (int i = 0; i < values.Length; i++) { qt[i] = new QuestionTag(); qt[i].questionId = question.Id; qt[i].tagId = tags[i].Id; db.QuestionTags.Add(qt[i]); } db.SaveChanges(); return RedirectToAction("Details", new { id = question.Id, title = ElectronicsController.URLFriendly(question.title) }); } ViewBag.postedBy = new SelectList(db.AspNetUsers, "Id", "Email", question.postedBy); return View(question); } return View(question); }
public void SaveQuestionTags(string s, Question q, bool update = false) { if (update) { var adid = q.Id; var adtags = db.QuestionTags.Where(x => x.questionId.Equals(adid)).ToList(); foreach (var cc in adtags) { db.QuestionTags.Remove(cc); } db.SaveChanges(); } string[] values = s.Split(','); Inspinia_MVC5_SeedProject.Models.Tag[] tags = new Inspinia_MVC5_SeedProject.Models.Tag[values.Length]; QuestionTag[] qt = new QuestionTag[values.Length]; for (int i = 0; i < values.Length; i++) { values[i] = values[i].Trim(); string ss = values[i]; if (ss != "") { var data = db.Tags.FirstOrDefault(x => x.name.Equals(ss, StringComparison.OrdinalIgnoreCase)); tags[i] = new Inspinia_MVC5_SeedProject.Models.Tag(); if (data != null) { tags[i].Id = data.Id; } else { tags[i].name = values[i]; tags[i].time = DateTime.UtcNow; tags[i].createdBy = System.Web.HttpContext.Current.User.Identity.GetUserId(); db.Tags.Add(tags[i]); } } else { tags[i] = null; } } try { db.SaveChanges(); } catch (Exception e) { string sb = e.ToString(); } for (int i = 0; i < values.Length; i++) { if (tags[i] != null) { qt[i] = new QuestionTag(); qt[i].questionId = q.Id; qt[i].tagId = tags[i].Id; db.QuestionTags.Add(qt[i]); } } try { db.SaveChanges(); } catch (Exception e) { string sb = e.ToString(); } }