Hi all in this article I would like to show you how to create a forums application using MVC4 and Entity Framework.

This application mainly covers the following:

  1. Registering a User.
  2. Login.
  3. Create questions on the technology available.
  4. Add reply's to the posted questions.
There were also several things included like getting the last reply posted for the question and also not allowing the user to post questions or replies without logging in.

The database for the current application has the necessary tables and Stored Procedures as follows:
  1. USE [newForumDB]
  2. GO
  3. /****** Object: Table [dbo].[tblUser] Script Date: 02/14/2013 14:21:09 ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. SET ANSI_PADDING ON
  9. GO
  10. CREATE TABLE [dbo].[tblUser](
  11. [UserName] [varchar](50) NOT NULL,
  12. [EmailID] [varchar](50) NOT NULL,
  13. [DisplayName] [varchar](50) NOT NULL,
  14. [DateJoined] [datetime] NOT NULL,
  15. [Password] [varchar](50) NOT NULL,
  16. [Photo] [image] NULL,
  17. CONSTRAINT [PK_tblUser] PRIMARY KEY CLUSTERED
  18. (
  19. [UserName] ASC
  20. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  21. ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
  22. GO
  23. SET ANSI_PADDING OFF
  24. GO
  25. USE [newForumDB]
  26. GO
  27. /****** Object: Table [dbo].[tblTechnology] Script Date: 02/14/2013 14:21:54 ******/
  28. SET ANSI_NULLS ON
  29. GO
  30. SET QUOTED_IDENTIFIER ON
  31. GO
  32. SET ANSI_PADDING ON
  33. GO
  34. CREATE TABLE [dbo].[tblTechnology](
  35. [TechID] [int] IDENTITY(1,1) NOT NULL,
  36. [TechName] [varchar](max) NOT NULL,
  37. [TechDesc] [varchar](100) NULL,
  38. PRIMARY KEY CLUSTERED
  39. (
  40. [TechID] ASC
  41. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  42. ) ON [PRIMARY]
  43. GO
  44. SET ANSI_PADDING OFF
  45. GO
  46. USE [newForumDB]
  47. GO
  48. /****** Object: Table [dbo].[tblQuestions] Script Date: 02/14/2013 14:22:06 ******/
  49. SET ANSI_NULLS ON
  50. GO
  51. SET QUOTED_IDENTIFIER ON
  52. GO
  53. SET ANSI_PADDING ON
  54. GO
  55. CREATE TABLE [dbo].[tblQuestions](
  56. [QuestionID] [int] IDENTITY(1,1) NOT NULL,
  57. [QuestionTitle] [varchar](max) NOT NULL,
  58. [QuestionDesc] [varchar](max) NOT NULL,
  59. [DatePosted] [datetime] NOT NULL,
  60. [UserName] [varchar](50) NOT NULL,
  61. [TechID] [int] NOT NULL,
  62. [viewCount] [int] NOT NULL,
  63. [ReplyCount] [int] NOT NULL,
  64. PRIMARY KEY CLUSTERED
  65. (
  66. [QuestionID] ASC
  67. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  68. ) ON [PRIMARY]
  69. GO
  70. SET ANSI_PADDING OFF
  71. GO
  72. SELECT [ReplyID]
  73. ,[QuestionID]
  74. ,[date]
  75. ,[TechID]
  76. ,[UserName]
  77. ,[ReplyMsg]
  78. FROM [newForumDB].[dbo].[tblReplies]
  79. GO
Stored Procedures
  1. USE [newForumDB]
  2. GO
  3. /****** Object: StoredProcedure [dbo].[displayallQuesTechID1] Script Date: 02/14/2013 14:23:05 ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. CREATE procedure [dbo].[displayallQuesTechID1](@TechID int
  9. )as
  10. begin
  11. select FI.QuestionID,FI.QuestionTitle,FI.UserName,FI.DatePosted,FI.[date],FI.RepliedName,FI.viewCount,FI.ReplyCount
  12. ,FI.ReplyMsg,TT.TechID,TT.TechName from tblTechnology TT,
  13. (select distinct TQ.TechID,TQ.QuestionID,TQ.QuestionTitle,TQ.UserName,TQ.DatePosted,TR.[date],TR.UserName as RepliedName,TQ.viewCount,TQ.ReplyCount
  14. ,TR.ReplyMsg from tblQuestions TQ LEFT OUTER JOIN tblReplies TR ON TR.TechID=TQ.TechID and TR.QuestionID = TQ.QUESTIONID
  15. and TR.[date]in (select MAX(TR.[date]) from tblReplies TR group by TR.QuestionID)) FI where FI.TechID=TT.TechID and TT.TechID=@TechID
  16. end
  17. GO
  18. USE [newForumDB]
  19. GO
  20. /****** Object: StoredProcedure [dbo].[displayResults] Script Date: 02/14/2013 14:23:38 ******/
  21. SET ANSI_NULLS ON
  22. GO
  23. SET QUOTED_IDENTIFIER ON
  24. GO
  25. CREATE procedure [dbo].[displayResults](@QuestionID int
  26. )as
  27. begin
  28. select tbl.QuestionID,tbl.QuestionDesc,tbl.TechID,tbl.quesaskedby,tbl.QuestionTitle,tbl.DatePosted,tbl.ReplyID,
  29. tbl.date,tbl.ReplyMsg,tbl.ReplyUser from
  30. (select distinct q.QuestionID,q.QuestionDesc,q.TechID, q.UserName as quesaskedby,q.QuestionTitle,q.DatePosted,
  31. r.date,r.ReplyID,r.ReplyMsg,r.UserName as ReplyUser
  32. from tblQuestions q left outer join tblReplies r on r.QuestionID=q.QuestionID) tbl
  33. where tbl.QuestionID=@QuestionID
  34. end
  35. GO
  36. USE [newForumDB]
  37. GO
  38. /****** Object: StoredProcedure [dbo].[selectTechQuestions1] Script Date: 02/14/2013 14:23:47 ******/
  39. SET ANSI_NULLS ON
  40. GO
  41. SET QUOTED_IDENTIFIER ON
  42. GO
  43. CREATE PROCEDURE [dbo].[selectTechQuestions1]
  44. As
  45. Begin
  46. WITH A AS (
  47. SELECT top(1) WITH ties Q.TechID
  48. ,QuestionID
  49. ,QuestionTitle
  50. ,DatePosted
  51. ,Username,TechName,TechDesc,T.TechID as TechnID
  52. FROM tblTechnology T LEFT OUTER JOIN tblQuestions Q ON Q.TechID = T.TechID
  53. ORDER BY row_number() over(partition BY Q.TechID ORDER BY Dateposted DESC)
  54. )
  55. SELECT * FROM A
  56. OUTER apply (SELECT count(QuestionDesc) Totalposts, sum(ReplyCount) ReplyCount
  57. FROM tblQuestions WHERE A.TechID=tblQuestions.TechID) D
  58. End
  59. GO

Ok now let's create an MVC application.

one.jpg
two.jpg
Open your "_ViewStart.cshtml" that is present in the "VIEWS->Shared" folder and replace the contents with the following:
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width" />
  6. <title>@ViewBag.Title</title>
  7. @Styles.Render("~/Content/css")
  8. @Scripts.Render("~/bundles/modernizr")
  9. <script src="@Url.Content("~/Scripts/tinymce/jquery.tinymce.js")" type="text/javascript"></script>
  10. </head>
  11. <body>
  12. <div id="branding">
  13. </div>
  14. <div>
  15. @if (Session["UserName"] != null)
  16. {
  17. <div class="logged_in" id="user_navigation" runat="server">
  18. <a title="Your Profile" href="">@*<img height="50" width="50" class="photo" src='<%= Url.Action( "GetPhoto", "image", new { photoId = Session["UserName"] } ) %>' />*@
  19. <img alt="" src="@Url.Action("GetPhoto", "User")" height="50" width="50" class="photo" />
  20. </a>
  21. <div id="user_info">
  22. <p>
  23. <span class="hide">Signed in as </span><a href="" title="Your Profile" class="ipbmenu">
  24. <span class="ipbmenu">@Html.Label("Name", Session["UserName"].ToString()) </span>
  25. </a>
  26. <img alt=">" src="http://www.gimptalk.com/public/style_images/master/opts_arrow.png" />
  27. </p>
  28. <ul class="boxShadow" id="user_link_menucontent" style="display: none; position: absolute;
  29. z-index: 9999;">
  30. </ul>
  31. <ul id="user_other">
  32. <li><a href="../User/Logout">Logout</a> </li>
  33. </ul>
  34. </div>
  35. <br />
  36. </div>
  37. @*<strong>@Html.Encode(User.Identity.Name)</strong>
  38. @Html.ActionLink("Log Out", "Logout", "User");*@
  39. }
  40. else
  41. {
  42. <div class="not_logged_in" id="user_navigation" runat="server">
  43. <a class="rounded" id="A1" title="Sign In »" href="../User/Login"><span class="left">
  44. Sign In »</span> <span class="services right"></span>
  45. <br />
  46. </a>
  47. <br />
  48. <span class="links">New user? <a id="register_link" title="Register Now!" href="../User/Register">
  49. Register Now!</a> </span>
  50. </div>
  51. }
  52. </div>
  53. <div id="primary_nav">
  54. <ul>
  55. <li class="left active" id="nav_discussion" runat="server"><a title="Go to Forums"
  56. href="@Url.Action("Main", "Home")">Forums</a></li><li class="left" id="nav_members"
  57. runat="server"><a
  58. title="Go to Member List" href="@Url.Action("Members", "Home")">Members</a></li>
  59. </ul>
  60. </div>
  61. @RenderBody()
  62. @Scripts.Render("~/bundles/jquery")
  63. @RenderSection("scripts", required: false)
  64. </body>
  65. </html>
If you would like to include your own scripts and CSS then open the "BundleConfig.cs" that is present in the "App_Start" folder and you will see CSS or scripts included that you need to add the following to:
  1. bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/css/ipb_common.css",
  2. "~/Content/css/ipb_editor.css",
  3. "~/Content/css/ipb_help.css",
  4. "~/Content/css/ipb_login_register.css",
  5. "~/Content/css/ipb_print.css",
  6. "~/Content/css/ipb_styles.css", "~/Content/css/ipb_ucp.css"));
Now let us create a Model with two classes, namely "userModel" and "Register".
three.jpg
four.jpg
Copy and paste the following code in your class and build the application.
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.ComponentModel.DataAnnotations;
  6. using System.ComponentModel.DataAnnotations.Schema;
  7. using System.Web.Mvc;
  8. namespace mvcForumapp.Models
  9. {
  10. public class userModel
  11. {
  12. [Required]
  13. [DataType(DataType.EmailAddress)]
  14. [Display(Name = "Email address")]
  15. [MaxLength(50)]
  16. [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
  17. public string Email { get; set; }
  18. [Required]
  19. [DataType(DataType.Password)]
  20. [Display(Name = "Password")]
  21. public string password { get; set; }
  22. }
  23. public class Register
  24. {
  25. [Required(ErrorMessage = "username required")]
  26. [Display(Name = "Choose username")]
  27. [StringLength(20, MinimumLength = 4)]
  28. [Remote("IsUserNameAvailable", "Register", "Username is already taken")]
  29. public string Username { get; set; }
  30. [Required(ErrorMessage = "display required")]
  31. [StringLength(20, MinimumLength = 4)]
  32. [Remote("IsDisplayAvailable", "Register", "displayname already taken")]
  33. public string Displayname { get; set; }
  34. [Required(ErrorMessage = "EmailAddress required")]
  35. [DataType(DataType.EmailAddress)]
  36. [Display(Name = "Email address")]
  37. [MaxLength(50)]
  38. [RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage = "Please enter correct email")]
  39. [Remote("IsEmailAvailable", "Register", "EmailAddress is already taken")]
  40. public string Email { get; set; }
  41. [Required(ErrorMessage = "password required")]
  42. [DataType(DataType.Password)]
  43. [StringLength(20, MinimumLength = 8)]
  44. [Display(Name = "Password")]
  45. public string password { get; set; }
  46. [Required(ErrorMessage = "password required")]
  47. [DataType(DataType.Password)]
  48. [Compare("password", ErrorMessage = "password didn't match")]
  49. [StringLength(20, MinimumLength = 8)]
  50. public string PasswordConfirm { get; set; }
  51. }
  52. }
Now let us create a controller and provide the name you need, or since we are initially trying to create and register a user, the name "UserController" is a better naming convention that will make your work easy in MVC otherwise we will encounter problems when we implement or work on large applications.
five.jpg
Name it "Register".
six.jpg
First let us work on user registeration. As I said, we are using Entity Framework to add an entity model to our project, from the tables and Stored Procedures that I provided, you can easily add an Entity Model to the application, Entity Framework beginners can check my previous articles explaining how to add a model to the project from here:
Now replace your controller code with the following
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.UI;
  7. namespace mvcForumapp.Controllers
  8. {
  9. public class UserController : Controller
  10. {
  11. //
  12. // GET: /User/
  13. newForumDBEntities db = new newForumDBEntities();
  14. public ActionResult Index()
  15. {
  16. return View();
  17. }
  18. [HttpGet]
  19. public ActionResult Register()
  20. {
  21. return View();
  22. }
  23. public ActionResult IsUserNameAvailable(string UserName)
  24. {
  25. var usrAvailable = db.tblUsers.Where(p => p.UserName == UserName).Select(img => img.UserName).FirstOrDefault();
  26. if (usrAvailable == null)
  27. {
  28. return Json(true, JsonRequestBehavior.AllowGet);
  29. }
  30. //string html = "<span style='color:Red;'> Username in use</span>";
  31. return Json("<span style='color:Red;'> Username in already in use</span>", JsonRequestBehavior.AllowGet);
  32. }
  33. [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
  34. public JsonResult IsDisplayAvailable(string Displayname)
  35. {
  36. var usrAvailable = db.tblUsers.Where(p => p.DisplayName == Displayname).Select(img => img.DisplayName).FirstOrDefault();
  37. if (usrAvailable == null)
  38. {
  39. return Json(true, JsonRequestBehavior.AllowGet);
  40. }
  41. //string html = "<span style='color:Red;'> Username in use</span>";
  42. return Json("<span style='color:Red;'> Display name in already use</span>", JsonRequestBehavior.AllowGet);
  43. }
  44. [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
  45. public JsonResult IsEmailAvailable(string Email)
  46. {
  47. var usrAvailable = db.tblUsers.Where(p => p.EmailID == Email).Select(img => img.EmailID).FirstOrDefault();
  48. if (usrAvailable == null)
  49. {
  50. return Json(true, JsonRequestBehavior.AllowGet);
  51. }
  52. //string html = "<span style='color:Red;'> Username in use</span>";
  53. return Json("<span style='color:Red;'> Emai in already in use</span>", JsonRequestBehavior.AllowGet);
  54. }
  55. [HttpPost]
  56. public ActionResult Register(mvcForumapp.Models.Register user, HttpPostedFileBase file)
  57. {
  58. if (ModelState.IsValid)
  59. {
  60. if (file == null)
  61. {
  62. ModelState.AddModelError("File", "Please Upload Your file");
  63. }
  64. else if (file.ContentLength > 0)
  65. {
  66. int MaxContentLength = 1024 * 1024 * 3; //3 MB
  67. string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
  68. if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
  69. {
  70. ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions));
  71. }
  72. else if (file.ContentLength > MaxContentLength)
  73. {
  74. ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB");
  75. }
  76. else
  77. {
  78. using (var db = new newForumDBEntities())
  79. {
  80. Byte[] imgByte = null;
  81. HttpPostedFileBase File = file;
  82. //Create byte Array with file len
  83. imgByte = new Byte[File.ContentLength];
  84. //force the control to load data in array
  85. File.InputStream.Read(imgByte, 0, File.ContentLength);
  86. var userdets = db.tblUsers.CreateObject();
  87. userdets.UserName = user.Username;
  88. userdets.DateJoined = DateTime.Now;
  89. userdets.DisplayName = user.Displayname;
  90. userdets.EmailID = user.Email;
  91. userdets.Password = user.password;
  92. userdets.Photo = imgByte;
  93. //var encrppass = Encrypt(user.password, true);
  94. //var userdets = db.tblUsers.CreateObject();
  95. //userdets.EmailID = user.Email;
  96. //userdets.password = encrppass;
  97. db.tblUsers.AddObject(userdets);
  98. db.SaveChanges();
  99. return RedirectToAction("Main", "Home");
  100. }
  101. }
  102. }
  103. }
  104. return View(user);
  105. }
  106. }
  107. }
Now let us create a View for registering inside the controller. There are two action results with the same name "Register" but the functionality is different, one is for HttpGet that just returns a view with controls and the other is for HttpPost to post the data to the database.
seven.jpg
eight.jpg
You can also create a strongly-type view by selecting the desired class from the drop-down and select create in the Scaffold template if you would like to have your own design just create an empty view.
Your view initially, if you didn't select a strongly-typed view, will be as follows:
  1. @{
  2. ViewBag.Title = "Register";
  3. Layout = "~/Views/Shared/_Layout.cshtml";
  4. }
Copy and paste the following:
  1. @model mvcForumapp.Models.Register
  2. @{
  3. ViewBag.Title = "Register";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
  7. <script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
  8. <script src="../../Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
  9. <script type="text/jscript">
  10. //get file size
  11. function GetFileSize(fileid) {
  12. try {
  13. var fileSize = 0;
  14. //for IE
  15. if ($.browser.msie) {
  16. //before making an object of ActiveXObject,
  17. //please make sure ActiveX is enabled in your IE browser
  18. var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
  19. var objFile = objFSO.getFile(filePath);
  20. var fileSize = objFile.size; //size in kb
  21. fileSize = fileSize / 1048576; //size in mb
  22. }
  23. //for FF, Safari, Opeara and Others
  24. else {
  25. fileSize = $("#" + fileid)[0].files[0].size //size in kb
  26. fileSize = fileSize / 1048576; //size in mb
  27. }
  28. // alert("Uploaded File Size is" + fileSize + "MB");
  29. return fileSize;
  30. }
  31. catch (e) {
  32. alert("Error is :" + e);
  33. }
  34. }
  35. //get file path from client system
  36. function getNameFromPath(strFilepath) {
  37. var objRE = new RegExp(/([^\/\\]+)$/);
  38. var strName = objRE.exec(strFilepath);
  39. if (strName == null) {
  40. return null;
  41. }
  42. else {
  43. return strName[0];
  44. }
  45. }
  46. $("#btnSubmit").live("click", function () {
  47. if ($('#fileToUpload').val() == "") {
  48. $("#spanfile").html("Please upload file");
  49. return false;
  50. }
  51. else {
  52. return checkfile();
  53. }
  54. });
  55. function checkfile() {
  56. var file = getNameFromPath($("#fileToUpload").val());
  57. if (file != null) {
  58. var extension = file.substr((file.lastIndexOf('.') + 1));
  59. // alert(extension);
  60. switch (extension) {
  61. case 'jpg':
  62. case 'JPG':
  63. case 'png':
  64. case 'PNG':
  65. case 'gif':
  66. case 'GIF':
  67. flag = true;
  68. break;
  69. default:
  70. flag = false;
  71. }
  72. }
  73. if (flag == false) {
  74. $("#spanfile").text("You can upload only jpg,png,gif,pdf extension file");
  75. return false;
  76. }
  77. else {
  78. var size = GetFileSize('fileToUpload');
  79. if (size > 3) {
  80. $("#spanfile").text("You can upload file up to 3 MB");
  81. return false;
  82. }
  83. else {
  84. $("#spanfile").text("");
  85. }
  86. }
  87. }
  88. $(function () {
  89. $("#fileToUpload").change(function () {
  90. checkfile();
  91. });
  92. });
  93. </script>
  94. @using (Html.BeginForm("Register", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
  95. {
  96. <br />
  97. <br />
  98. <div class="block_wrap left" id="register_form">
  99. <h2>
  100. Ready to register?</h2>
  101. <p class="extra">
  102. It's free and simple to register for our board! We just need
  103. a few pieces of information from you, and you'll be ready to
  104. make your first post in no time!
  105. <br />
  106. If you already have an account, you can go directly to the <a
  107. title="Go to sign in" href="../User/Login">sign in page</a>
  108. <br />
  109. </p>
  110. <div class="generic_bar">
  111. </div>
  112. <h3 style="text-align: center;" class="bar">
  113. Account Information</h3>
  114. <ul>
  115. <li class="field required ">
  116. @Html.LabelFor(m => m.Username)
  117. @Html.TextBoxFor(m => m.Username, new { maxlength = 50 })
  118. <span class="input_error">@Html.ValidationMessageFor(m => m.Username)</span>
  119. </li>
  120. <li class="field required ">
  121. @Html.LabelFor(m => m.Displayname)
  122. @Html.TextBoxFor(m => m.Displayname, new { maxlength = 50 })
  123. <span class="input_error">@Html.ValidationMessageFor(m => m.Displayname)</span>
  124. </li>
  125. <li class="field required ">
  126. @Html.LabelFor(m => m.Email)
  127. @Html.TextBoxFor(m => m.Email, new { maxlength = 50 })
  128. <span class="input_error">@Html.ValidationMessageFor(m => m.Email)</span>
  129. </li>
  130. <li class="field required ">
  131. @Html.LabelFor(m => m.password)
  132. @Html.PasswordFor(m => m.password, new { maxlength = 50 })
  133. <span class="input_error">@Html.ValidationMessageFor(m => m.password)</span>
  134. </li>
  135. <li class="field required ">
  136. @Html.LabelFor(m => m.PasswordConfirm)
  137. @Html.PasswordFor(m => m.PasswordConfirm, new { maxlength = 50 })
  138. <span class="input_error">@Html.ValidationMessageFor(m => m.PasswordConfirm)</span>
  139. </li>
  140. <li class="field required ">
  141. <label>
  142. Select Image</label>
  143. <input type="file" id="fileToUpload" name="file" />
  144. <span class="input_error" id="spanfile"></span></li>
  145. </ul>
  146. <br />
  147. <hr />
  148. <div style="float: left; margin-left: 250px;">
  149. <table>
  150. <tr>
  151. <td>
  152. <input type="submit" class="input_submit" id="btnSubmit" value="Create User" />
  153. </td>
  154. <td>
  155. @Html.ActionLink("Cancel", "Main", new { Controller = "Home" }, new { @class = "input_submit" })
  156. </td>
  157. </tr>
  158. </table>
  159. @*<input type="submit" value=" Cancel" class="input_submit" />*@
  160. </div>
  161. </div>
  162. <br />
  163. <div style="float: right; margin-right: 350px;">
  164. </div>
  165. }
Changes in "RouteConfig.cs" that is in the "App_Start" folder:
  1. public static void RegisterRoutes(RouteCollection routes)
  2. {
  3. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  4. routes.MapRoute(
  5. name: "Default",
  6. url: "{controller}/{action}/{id}",
  7. defaults: new { controller = "User", action = "Index", id = UrlParameter.Optional }
  8. );
  9. }
Now run the application and you will be shown the following:
main.jpg

Clicking on "Register" will route to the Register view and "Login" will route to the Login view.

This is how the register view looks:

register.jpg
validations.jpg
Remote validation:
Check here for the implementation of remote validation http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx
Here I checked whether Username, displayname and email exist, if the do not exist then remote validation fires if not then it will not show an error.
remote.jpg
If everything is fine then you are ready to register.
mvcuse.jpg
After you are registered, it will route back to the default page.
Now let us work on Login as you already create a Model let us work on creating a controller for Login and required Views.
Follow as we do for Register starting from the controller, first add a controller named "logincontroller" in the "Controller" folder then replace it with the following code:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace mvcForumapp.Controllers
  7. {
  8. public class LoginController : Controller
  9. {
  10. newForumDBEntities db = new newForumDBEntities();
  11. [HttpGet]
  12. public ActionResult Login()
  13. {
  14. return View();
  15. }
  16. [HttpPost]
  17. public ActionResult Login(mvcForumapp.Models.userModel user)
  18. {
  19. if (ModelState.IsValid)
  20. {
  21. if (isValid(user.Email, user.password))
  22. {
  23. var user1 = db.tblUsers.FirstOrDefault(u => u.EmailID == user.Email).UserName;
  24. Session["UserName"] = user1;
  25. //FormsAuthentication.SetAuthCookie(user.Email, false);
  26. return RedirectToAction("Index", "Register");
  27. }
  28. else
  29. {
  30. ModelState.AddModelError("", "Login Data is Incorrect");
  31. }
  32. }
  33. return View(user);
  34. }
  35. private bool isValid(string Email, string password)
  36. {
  37. //string crypto = Encrypt(password, true);
  38. bool isvalid = false;
  39. using (var db = new newForumDBEntities())
  40. {
  41. var user = db.tblUsers.FirstOrDefault(u => u.EmailID == Email);
  42. if (user != null)
  43. {
  44. if (user.Password == password)
  45. {
  46. isvalid = true;
  47. }
  48. }
  49. }
  50. return isvalid;
  51. }
  52. }
  53. }
Add Views correspondingly as we did for "Register", after adding the view your login view your run will look as follows:
login.jpg
After successful login you will be shown your user name along with your image as follows, before that ensure you implement code for showing the image of the user logging in; we will implement that as follows.
You will see your "_Layout.cshtml" as follows:
  1. <img alt="" src="@Url.Action("GetPhoto", "User")" height="50" width="50" class="photo" />
This means we are trying to load the image from the "controller(User)" with the method or function name "GetPhoto"; change it as per your controller and method here. For a better understanding I will create a new controller and name it "displayImage" with the function "ShowImage" so my image source will be as follows:
now <img alt="" src="@Url.Action("ShowImage", "displayImage")" height="50" width="50" class="photo" />
Your controller code to display the login user image is as follows:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace mvcForumapp.Controllers
  7. {
  8. public class displayImageController : Controller
  9. {
  10. //
  11. // GET: /displayImage/
  12. newForumDBEntities db = new newForumDBEntities();
  13. public ActionResult Index()
  14. {
  15. return View();
  16. }
  17. [HttpGet]
  18. public ActionResult ShowImage()
  19. {
  20. string user = Session["UserName"] as string;
  21. byte[] photo = null;
  22. var v = db.tblUsers.Where(p => p.UserName == user).Select(img => img.Photo).FirstOrDefault();
  23. photo = v;
  24. return File(photo, "image/jpeg");
  25. }
  26. }
  27. }
Here is what you will see after a successful login:
disp.jpg
Now let us create a controller and a view for logout. Create a controller and name it "Logout" and then replace your controller with the following:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace mvcForumapp.Controllers
  7. {
  8. public class LogoutController : Controller
  9. {
  10. //
  11. // GET: /Logout/
  12. public ActionResult Logout()
  13. {
  14. Session.Abandon();
  15. return RedirectToAction("Index", "Register");
  16. }
  17. }
  18. }
Now add a view by right-clicking on the "Logout" action result and select the master page. Your view should be as follows:
  1. @{
  2. ViewBag.Title = "Logout";
  3. Layout = "~/Views/Shared/_Layout.cshtml";
  4. }
  5. <h2>Logout</h2>
After successful log-out you will be routed to the main view again.
So far so good. Now let us create Controllers and Views for the rest, i.e posting questions, replies and all. First let us bring all the Questions from the database from each technology.

As we are using Entity Framework each and every Stored Procedure from the database is treated as a model, not only Stored Procedures but also tables.

First let us create a controller for displaying the list of technologies available and the number of topics and replies under each technology, also the last posted question information.
Create a controller and name it "Technology" and replace the code with the following code:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. namespace mvcForumapp.Controllers
  7. {
  8. public class TechnologyController : Controller
  9. {
  10. //
  11. // GET: /Technology/
  12. newForumDBEntities db = new newForumDBEntities();
  13. public ActionResult Index()
  14. {
  15. List<mvcForumapp.selectStats_Result_Result> userview = db.selectStats_Result().ToList();
  16. return View(userview);
  17. }
  18. }
  19. }
Create an empty View by right-clicking on "Index" and replace the view with the following:
  1. @model IEnumerable<mvcForumapp.selectStats_Result_Result>
  2. @{
  3. ViewBag.Title = "Main";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. <div id="secondary_nav">
  7. <ul class="left" id="breadcrumb">
  8. <li class="first"><a href="">MVC-Forum Community</a></li>
  9. </ul>
  10. </div>
  11. <div class="clear" id="content">
  12. <a id="j_content"></a>
  13. <h2 class="hide">
  14. Board Index</h2>
  15. <div class="clearfix" id="board_index">
  16. <div class="no_sidebar clearfix" id="categories">
  17. <!-- CATS AND FORUMS -->
  18. <div class="category_block block_wrap">
  19. <h3 class="maintitle" id="category_47">
  20. <a title="View category" href="../Home/Main">Technology related questions</a></h3>
  21. <div class="table_wrap">
  22. <table summary="Forums within the category 'GimpTalk'" class="ipb_table">
  23. <tbody>
  24. <tr class="header">
  25. <th class="col_c_icon" scope="col">
  26. </th>
  27. <th class="col_c_forum" scope="col">
  28. Forum
  29. </th>
  30. <th class="col_c_stats stats" scope="col">
  31. Stats
  32. </th>
  33. <th class="col_c_post" scope="col">
  34. Last Post Info
  35. </th>
  36. </tr>
  37. <tr class="row1">
  38. <td class="altrow">
  39. </td>
  40. <td>
  41. @foreach (var item in Model)
  42. {
  43. string techname = item.TechName;
  44. @Html.ActionLink(techname, "Details", "Home", new { TechID = item.TechnID }, null)
  45. <br />
  46. <br />
  47. @Html.DisplayFor(modelItem => item.TechDesc)
  48. <br />
  49. <br />
  50. }
  51. </td>
  52. <td class="altrow stats">
  53. @foreach (var item in Model)
  54. {
  55. @Html.DisplayFor(modelItem => item.Totalposts)
  56. @Html.Label(" ");
  57. @Html.Label("Topics")
  58. <br />
  59. if (item.ReplyCount != null)
  60. {
  61. @Html.DisplayFor(modelItem => item.ReplyCount)
  62. @Html.Label(" ");
  63. @Html.Label("Replies")
  64. <br />
  65. <br />
  66. }
  67. else
  68. {
  69. @Html.DisplayFor(modelItem => item.ReplyCount)
  70. @Html.Label(" ");
  71. @Html.Label("0 Replies")
  72. <br />
  73. <br />
  74. }
  75. }
  76. </td>
  77. <td>
  78. @foreach (var item in Model)
  79. {
  80. if (item.DatePosted != null)
  81. {
  82. DateTime dt = Convert.ToDateTime(item.DatePosted);
  83. string strDate = dt.ToString("dd MMMM yyyy - hh:mm tt");
  84. @Html.Label(strDate)
  85. <br />
  86. }
  87. else
  88. {
  89. <br />
  90. }
  91. if (item.QuestionTitle != null)
  92. {
  93. @Html.Label("IN : ");
  94. @Html.Label(" ");
  95. string QuestionTitle = item.QuestionTitle;
  96. @Html.ActionLink(QuestionTitle, "displayIndividual", "Display", new { QuestionID = item.QuestionID }, null)
  97. <br />
  98. }
  99. else
  100. {
  101. <br />
  102. }
  103. if (item.Username != null)
  104. {
  105. @Html.Label("By : ");
  106. @Html.Label(" ");
  107. string User = item.Username;
  108. @Html.ActionLink(User, "Details", "Home", new { Username = item.Username }, null)
  109. <br />
  110. <br />
  111. }
  112. else
  113. {
  114. @Html.ActionLink("Start New Topic", "PostQuestion", "Home", new { TechID = item.TechnID }, null)
  115. <br />
  116. <br />
  117. }
  118. }
  119. </td>
  120. </tr>
  121. </tbody>
  122. </table>
  123. </div>
  124. </div>
  125. </div>
  126. </div>
  127. </div>
Earlier I set the default routing view as Index from Register, so let us change that so when someone hits, the default view will be shown with the list of questions.

Changes in "RouteConfig.cs" that is in the "App_Start" folder:
  1. public static void RegisterRoutes(RouteCollection routes)
  2. {
  3. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  4. routes.MapRoute(
  5. name: "Default",
  6. url: "{controller}/{action}/{id}",
  7. defaults: new { controller = "Technology", action = "Index", id = UrlParameter.Optional }
  8. );
  9. }
This is how your view looks when you run the application:
tech.jpg
Ok since I have questions in each and every Technology, this was displayed. Add a new technology in the tblTechnology table and run your application, when there are no question in that technology you will have a chance to post new questions in that technology.
start.jpg
Currently we haven't implemented anything for that; it will show an error page instead. We will see how to post new questions later on. First let me show you how to display all questions available in the selected Technology.
For the existing "Technology" controller I will add a few methods or you can add a new controller if you need to. I am adding the "a" method to the existing controller i.e "Technology" as follows:
  1. public ActionResult DisplayQuestions()
  2. {
  3. int TechID = Convert.ToInt16(Request.QueryString["TechID"].ToString());
  4. List<mvcForumapp.QuestionList_Result> disp = db.QuestionList(TechID).ToList();
  5. return View(disp);
  6. }
Create a view by right-clicking on "DisplayQuestions" and replace it with the following code:
  1. @model IEnumerable<mvcForumapp.QuestionList_Result>
  2. @{
  3. ViewBag.Title = "Details";
  4. }
  5. <style type="text/css">
  6. .disabled
  7. {
  8. /* Text and background colour, medium red on light yellow */
  9. float: right;
  10. margin-right: 20px;
  11. background: #999;
  12. background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#dadada), to(#f3f3f3));
  13. border-top: 1px solid #c5c5c5;
  14. border-right: 1px solid #cecece;
  15. border-bottom: 1px solid #d9d9d9;
  16. border-left: 1px solid #cecece;
  17. color: #8f8f8f;
  18. box-shadow: none;
  19. -moz-box-shadow: none;
  20. -webkit-box-shadow: none;
  21. cursor: not-allowed;
  22. text-shadow: 0 -1px 1px #ebebeb;
  23. }
  24. .active
  25. {
  26. box-shadow: none;
  27. -moz-box-shadow: none;
  28. -webkit-box-shadow: none;
  29. cursor: allowed;
  30. }
  31. </style>
  32. <br />
  33. <br />
  34. <div style="float: left; margin-left: 20px;">
  35. @Html.ActionLink("Back", "Index", "Technology")
  36. </div>
  37. <div id='ipbwrapper'>
  38. <ul class="comRigt">
  39. <li>
  40. <br />
  41. <img alt="Start New Topic" src="http://www.gimptalk.com/public/style_images/master/page_white_add.png" />
  42. @if (Session["UserName"] != null)
  43. {
  44. int techID = Convert.ToInt16(@Request.QueryString["TechID"]);
  45. if (Model.Count() == 0)
  46. {
  47. @Html.ActionLink("Start New Topic", "PostQuestion", "Question", new { @class = "active", onclick = "javascript:return true;", TechID = techID }, null)
  48. }
  49. else
  50. {
  51. foreach (var item in Model)
  52. {
  53. @Html.ActionLink("Start New Topic", "PostQuestion", "Question", new { @class = "active", onclick = "javascript:return true;", TechID = item.TechID }, null)
  54. break;
  55. }
  56. }
  57. }
  58. else
  59. {
  60. int techID = Convert.ToInt16(@Request.QueryString["TechID"]);
  61. if (Model.Count() == 0)
  62. {
  63. @Html.ActionLink("Start New Topic", "PostQuestion", "Home", new {title = "Please login to post Questions", @class = "disabled", onclick = "javascript:return false;", TechID = techID })
  64. }
  65. else
  66. {
  67. foreach (var item in Model)
  68. {
  69. @Html.ActionLink("Start New Topic", "PostQuestion", "Home", new {title = "Please login to post Questions", TechID = item.TechID, @class = "disabled", onclick = "javascript:return false;" })
  70. break;
  71. }
  72. }
  73. }
  74. </li>
  75. </ul>
  76. <br />
  77. @if (Model.Count() != 0)
  78. {
  79. <div class="category_block block_wrap">
  80. <table id="forum_table" summary="Topics In This Forum "GimpTalk News and Updates""
  81. class="ipb_table topic_list">
  82. <div class="maintitle">
  83. <span class="main_forum_title">
  84. @foreach (var item in Model)
  85. {
  86. string strTopic = "A forum where you can post questions regarding " + item.TechName;
  87. @Html.Label("Topic", strTopic)
  88. break;
  89. }
  90. </span>
  91. </div>
  92. <tbody>
  93. <tr class="header">
  94. <th class="col_f_icon" scope="col">
  95. </th>
  96. <th class="col_f_topic" scope="col">
  97. Topic
  98. </th>
  99. <th class="col_f_starter short" scope="col">
  100. Started By
  101. </th>
  102. <th class="col_f_views stats" scope="col">
  103. Stats
  104. </th>
  105. <th class="col_f_post" scope="col">
  106. Last Post Info
  107. </th>
  108. </tr>
  109. <tr id="trow_49752" class="row1">
  110. <td class="short altrow">
  111. </td>
  112. <td class="__topic __tid49752" id="anonymous_element_3">
  113. @foreach (var item in Model)
  114. {
  115. <br />
  116. string QuestionTitle = item.QuestionTitle;
  117. @Html.ActionLink(QuestionTitle, "displayIndividual", "Display", new { QuestionID = item.QuestionID }, null)
  118. <br />
  119. <br />
  120. }
  121. </td>
  122. <td class="short altrow">
  123. @foreach (var item in Model)
  124. {
  125. <br />
  126. string QuestionTitle = item.UserName;
  127. @Html.ActionLink(QuestionTitle, "Details", "Home", new { Username = item.UserName }, null)
  128. <br />
  129. <br />
  130. }
  131. </td>
  132. <td class="stats">
  133. <ul>
  134. <li>
  135. @foreach (var item in Model)
  136. {
  137. @Html.DisplayFor(modelItem => item.ReplyCount)
  138. @Html.Label(" ");
  139. @Html.Label("Replies")
  140. <br />
  141. @Html.DisplayFor(modelItem => item.viewCount)
  142. @Html.Label(" ");
  143. @Html.Label("Views")
  144. <br />
  145. <br />
  146. }
  147. </li>
  148. </ul>
  149. </td>
  150. <td class="altrow">
  151. @foreach (var item in Model)
  152. {
  153. if (item.date != null)
  154. {
  155. DateTime dt = Convert.ToDateTime(item.date);
  156. string strDate = dt.ToString("dd MMMM yyyy - hh:mm tt");
  157. @Html.Label(strDate)
  158. }
  159. else
  160. {
  161. DateTime dt = Convert.ToDateTime(item.DatePosted);
  162. string strDate = dt.ToString("dd MMMM yyyy - hh:mm tt");
  163. @Html.Label(strDate)
  164. }
  165. <br />
  166. @Html.Label("By : ")
  167. @Html.Label(" ")
  168. if (item.RepliedName != null)
  169. {
  170. string User = item.RepliedName;
  171. @Html.ActionLink(User, "Details", "Home", new { Username = item.RepliedName }, null)
  172. }
  173. else
  174. {
  175. string User = item.UserName;
  176. @Html.ActionLink(User, "Details", "Home", new { Username = item.UserName }, null)
  177. }
  178. <br />
  179. <br />
  180. }
  181. </td>
  182. </tr>
  183. </tbody>
  184. </table>
  185. </div>
  186. }
  187. else
  188. {
  189. <div class="category_block block_wrap">
  190. <table id="forum_table1" summary="Topics In This Forum "GimpTalk News and Updates""
  191. class="ipb_table topic_list">
  192. <div class="maintitle">
  193. <span style="font-size:larger; margin-left:450px;">No topics available</span>
  194. </div>
  195. </table>
  196. </div>
  197. }
  198. @if (Model.Count() != 0)
  199. {
  200. <ul class="comRigt">
  201. <li>
  202. <br />
  203. <img alt="Start New Topic" src="http://www.gimptalk.com/public/style_images/master/page_white_add.png" />
  204. @if (Session["UserName"] != null)
  205. {
  206. foreach (var item in Model)
  207. {
  208. @Html.ActionLink("Start New Topic", "PostQuestion", "Question", new { @class = "active", onclick = "javascript:return true;", TechID = item.TechID }, null)
  209. break;
  210. }
  211. }
  212. else
  213. {
  214. foreach (var item in Model)
  215. {
  216. @Html.ActionLink("Start New Topic", "PostQuestion", "Home", new {title = "Please login to post Questions", TechID = item.TechID, @class = "disabled", onclick = "javascript:return false;" })
  217. break;
  218. }
  219. }
  220. </li>
  221. </ul>
  222. }
  223. </div>
What will happen is, by selecting a particular technology in the image above will display all the questions related to that technology.
questins.jpg
In this you can start a new Topic or post a new question if the user was logged in.
So far so good. Let us create the final step in this i.e creating questions and posting replies, first let us see how to create questions.
Create a class in the model with the name "Questions"; your class should be as follows:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.ComponentModel.DataAnnotations;
  6. namespace mvcForumapp.Models
  7. {
  8. public class Questions
  9. {
  10. [Required(ErrorMessage = "Title required")]
  11. [Display(Name = "Enter Title")]
  12. [StringLength(20, MinimumLength = 4)]
  13. public string TopicTitle { get; set; }
  14. [Required(ErrorMessage = "Description required")]
  15. [Display(Name = "Enter Description")]
  16. [StringLength(20, MinimumLength = 10)]
  17. public string TopicDescription { get; set; }
  18. [Required(ErrorMessage = "Content required")]
  19. [StringLength(Int32.MaxValue, MinimumLength = 10)]
  20. public string TopicContent { get; set; }
  21. }
  22. }
Create a controller with the name "Question" and replace the code with this:
  1. public class QuestionController : Controller
  2. {
  3. [HttpGet]
  4. public ActionResult PostQuestion()
  5. {
  6. int techID = Convert.ToInt16(Request.QueryString["TechID"].ToString());
  7. return View();
  8. }
  9. }
This is how it is viewed when you route to the "PostQuestion" view:
postques.jpg
Create another method in the same controller with HttpPost to post the question:
  1. [HttpPost]
  2. public ActionResult PostQuestion(mvcForumapp.Models.Questions user)
  3. {
  4. int techID = 0;
  5. if (ModelState.IsValid)
  6. {
  7. techID = Convert.ToInt16(Request.QueryString["TechID"].ToString());
  8. using (var db = new newForumDBEntities())
  9. {
  10. var userdets = db.tblQuestions.CreateObject();
  11. userdets.TechID = Convert.ToInt16(Request.QueryString["TechID"].ToString());
  12. userdets.QuestionTitle = user.TopicTitle;
  13. userdets.QuestionDesc = user.TopicContent;
  14. userdets.DatePosted = DateTime.Now;
  15. userdets.UserName = Session["UserName"].ToString();
  16. userdets.viewCount = 0;
  17. userdets.ReplyCount = 0;
  18. db.tblQuestions.AddObject(userdets);
  19. db.SaveChanges();
  20. return RedirectToAction("DisplayQuestions", "Technology", new { TechID = techID });
  21. }
  22. }
  23. return View(user);
  24. }
After a successful post you will be routed to the list of questions for that technology.
You can do the same for replys by creating a class in "Model" with a name called "Replys" and adding the necessary for that. This is how it is displayed when a post has replys.

For viewing the questions with replies add "View" and "Controller" correspondingly and your code should be as follows in the controller:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Data.SqlClient;
  7. using System.Data;
  8. namespace mvcForumapp.Controllers
  9. {
  10. public class Question_AnswerController : Controller
  11. {
  12. newForumDBEntities db = new newForumDBEntities();
  13. int vwcnt = 0;
  14. [HttpGet]
  15. public ActionResult displayQuestionwithAnswers()
  16. {
  17. var paramQuesID = new SqlParameter("@QuestionID", SqlDbType.Int);
  18. var paramRepCnt = new SqlParameter("@viewcount", SqlDbType.Int);
  19. int quesID = Convert.ToInt16(Request.QueryString["QuestionID"].ToString());
  20. paramQuesID.Value = quesID;
  21. var viewcount = db.tblQuestions.Where(e1 => e1.QuestionID == quesID).FirstOrDefault();
  22. vwcnt = viewcount.viewCount;
  23. if (vwcnt == 0)
  24. {
  25. vwcnt++;
  26. paramRepCnt.Value = vwcnt;
  27. var v = db.ExecuteStoreCommand("UPDATE tblQuestions SET viewCount = @viewcount WHERE QuestionID = @QuestionID", paramRepCnt, paramQuesID);
  28. }
  29. else
  30. {
  31. vwcnt = vwcnt + 1;
  32. paramRepCnt.Value = vwcnt;
  33. var v = db.ExecuteStoreCommand("UPDATE tblQuestions SET viewCount = @viewcount WHERE QuestionID = @QuestionID", paramRepCnt, paramQuesID);
  34. }
  35. List<mvcForumapp.Questionwithreplys_Result> disp = db.Questionwithreplys(quesID).ToList();
  36. return View(disp);
  37. }
  38. [HttpGet]
  39. public ActionResult GetPhoto()
  40. {
  41. //RouteData.Values["QuesID"]
  42. int quesID = Convert.ToInt16(Request.QueryString["QuestionID"]);
  43. byte[] photo = null;
  44. var usrname = (from a in db.tblQuestions
  45. where a.QuestionID == quesID
  46. select new { a.UserName });
  47. var v = db.tblUsers.Where(p => p.UserName == usrname.FirstOrDefault().UserName).Select(img => img.Photo).FirstOrDefault();
  48. photo = v;
  49. return File(photo, "image/jpeg");
  50. }
  51. [HttpGet]
  52. public ActionResult ReplyPhoto()
  53. {
  54. //RouteData.Values["QuesID"]
  55. int quesID = Convert.ToInt16(Request.QueryString["QuestionID"]);
  56. byte[] photo = null;
  57. var usrname = (from a in db.tblReplies
  58. where a.ReplyID == quesID
  59. select new { a.UserName });
  60. var v = db.tblUsers.Where(p => p.UserName == usrname.FirstOrDefault().UserName).Select(img => img.Photo).FirstOrDefault();
  61. photo = v;
  62. return File(photo, "image/jpeg");
  63. }
  64. }
  65. }
View for the corresponding controller:
  1. @model IEnumerable<mvcForumapp.Questionwithreplys_Result>
  2. @{
  3. ViewBag.Title = "Index";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. }
  6. <style type="text/css">
  7. .disabled
  8. {
  9. /* Text and background colour, medium red on light yellow */
  10. float: right;
  11. margin-right: 20px;
  12. background: #999;
  13. background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#dadada), to(#f3f3f3));
  14. border-top: 1px solid #c5c5c5;
  15. border-right: 1px solid #cecece;
  16. border-bottom: 1px solid #d9d9d9;
  17. border-left: 1px solid #cecece;
  18. color: #8f8f8f;
  19. box-shadow: none;
  20. -moz-box-shadow: none;
  21. -webkit-box-shadow: none;
  22. cursor: not-allowed;
  23. text-shadow: 0 -1px 1px #ebebeb;
  24. }
  25. .active
  26. {
  27. box-shadow: none;
  28. -moz-box-shadow: none;
  29. -webkit-box-shadow: none;
  30. cursor: allowed;
  31. }
  32. </style>
  33. <br />
  34. <div style="float: left; margin-left: 20px;">
  35. @foreach (var item in Model)
  36. {
  37. @Html.ActionLink("Back", "DisplayQuestions", "Technology", new { TechID = item.TechID }, null)
  38. break;
  39. }
  40. </div>
  41. <div class="topic_controls">
  42. <br />
  43. <ul class="comRigt" runat="server" id="lnkTopic">
  44. <li>
  45. <img alt="Add Reply" src="http://www.gimptalk.com/public/style_images/master/arrow_rotate_clockwise.png" />
  46. @if (Session["UserName"] != null)
  47. {
  48. foreach (var item in Model)
  49. {
  50. @Html.ActionLink("Add Reply", "PostReply", "Home", new { @class = "active", onclick = "javascript:return true;", QuestionID = item.QuestionID, TechID = item.TechID }, null)
  51. break;
  52. }
  53. }
  54. else
  55. {
  56. foreach (var item in Model)
  57. {
  58. @Html.ActionLink("Add Reply", "PostReply", "Home", new { title = "Please login to post replys", TechID = item.QuestionID, @class = "disabled", onclick = "javascript:return false;" })
  59. break;
  60. }
  61. }
  62. </li>
  63. </ul>
  64. <br />
  65. <h2 class="maintitle">
  66. <span class="main_topic_title">
  67. @foreach (var item in Model)
  68. {
  69. string strTopic = item.QuestionTitle;
  70. @Html.Label("Topic", strTopic)
  71. break;
  72. }
  73. </span>
  74. </h2>
  75. <br />
  76. <div class="post_wrap">
  77. <h3>
  78. <span class="author vcard">
  79. @foreach (var item in Model)
  80. {
  81. string User = item.quesaskedby;
  82. @Html.ActionLink(User, "Details", "Home", new { Username = item.quesaskedby }, null)
  83. break;
  84. }
  85. @*<asp:linkbutton id="lnkUsername" runat="server" text='<%#Eval("UserName") %>' font-underline="false"></asp:linkbutton>*@
  86. </span>
  87. </h3>
  88. <div class="authornew">
  89. <ul>
  90. <li class="avatar">
  91. @foreach (var item in Model)
  92. {
  93. <img alt="" src="@Url.Action("GetPhoto", "Question_Answer", new { QuestionID = item.QuestionID })" height="100" width="100" class="photo" />
  94. break;
  95. }
  96. </li>
  97. </ul>
  98. </div>
  99. <div class="postbody">
  100. <p class="postnew">
  101. @foreach (var item in Model)
  102. {
  103. DateTime dt = Convert.ToDateTime(item.DatePosted);
  104. string strDate = dt.ToString("dd MMMM yyyy - hh:mm tt");
  105. @Html.Label(strDate)
  106. break;
  107. }
  108. @*<asp:label id="lblDateposted" text='<%#Eval("DatePosted") %>' font-underline="false"
  109. runat="server" cssclass="edit"></asp:label>*@
  110. </p>
  111. <br />
  112. <br />
  113. <div class="post entry-content ">
  114. @*<asp:label id="Label1" text='<%#Eval("QuestionDesc") %>' font-underline="false" runat="server"
  115. cssclass="edit"></asp:label>*@
  116. @foreach (var item in Model)
  117. {
  118. @Html.Label(item.QuestionDesc)
  119. break;
  120. }
  121. </div>
  122. </div>
  123. </div>
  124. <br />
  125. <br />
  126. <br />
  127. <ul style="background-color: #e4ebf3; text-align: right; background-image: url(http://www.gimptalk.com/public/style_images/master/gradient_bg.png);
  128. background-repeat: repeat-x; background-position: 40%; font-size: 1em; text-align: right;
  129. padding: 6px 10px 10px 6px; clear: both;">
  130. <li>
  131. <img alt="Add Reply" src="http://www.gimptalk.com/public/style_images/master/comment_add.png" />
  132. @if (Session["UserName"] != null)
  133. {
  134. foreach (var item in Model)
  135. {
  136. @Html.ActionLink("Add Reply", "PostReply", "Home", new { @class = "active", onclick = "javascript:return true;", QuestionID = item.QuestionID, TechID = item.TechID }, null)
  137. break;
  138. }
  139. }
  140. else
  141. {
  142. foreach (var item in Model)
  143. {
  144. @Html.ActionLink("Add Reply", "PostReply", "Home", new { title = "Please login to post replys", @class = "disabled", onclick = "javascript:return false;", TechID = item.QuestionID })
  145. break;
  146. }
  147. }
  148. @*<asp:linkbutton id="lnkpostReply" runat="server" onclick="lnkpostReply_Click" text="Reply"></asp:linkbutton>*@
  149. </li>
  150. </ul>
  151. </div>
  152. <br />
  153. <br />
  154. <div>
  155. @foreach (var item in Model)
  156. {
  157. if (item.ReplyUser != null)
  158. {
  159. <div class="topic_controls">
  160. <div class="post_wrap">
  161. <h3>
  162. @if (item.ReplyUser != null)
  163. {
  164. <span class="author vcard">
  165. @Html.ActionLink(item.ReplyUser.ToString(), "Details", "Home", new { Username = item.ReplyUser },
  166. null)</span>
  167. }
  168. <br />
  169. @*<asp:linkbutton id="lnkUsername" runat="server" text='<%#Eval("UserName") %>' font-underline="false"></asp:linkbutton>*@
  170. </h3>
  171. <div class="authornew">
  172. <ul>
  173. <li class="avatar">
  174. @if (item.ReplyID != null)
  175. {
  176. <img alt="" src="@Url.Action("ReplyPhoto", "Question_Answer", new { QuestionID = item.ReplyID })"
  177. height="100" width="100" class="photo" />
  178. }
  179. <br />
  180. </li>
  181. </ul>
  182. </div>
  183. <div class="postbody">
  184. <p class="postnew">
  185. @if (item.date != null)
  186. {
  187. @Html.Label(item.date.Value.ToString("dd MMMM yyyy - hh:mm tt"))
  188. }
  189. <br />
  190. @*<asp:label id="lblDateposted" text='<%#Eval("DatePosted") %>' font-underline="false"
  191. runat="server" cssclass="edit"></asp:label>*@
  192. </p>
  193. <br />
  194. <br />
  195. <div class="post
  196. entry-content ">
  197. @if (item.ReplyMsg != null)
  198. {
  199. @Html.Label(item.ReplyMsg)
  200. }
  201. <br />
  202. </div>
  203. @if (item.ReplyID != null)
  204. {
  205. <ul style="background-color: #e4ebf3; text-align: right; background-image: url(http://www.gimptalk.com/public/style_images/master/gradient_bg.png);
  206. background-repeat: repeat-x; background-position: 40%; font-size: 1em; text-align: right;
  207. padding: 6px 10px 10px 6px; clear: both;">
  208. <li>
  209. <img alt="Add Reply" src="http://www.gimptalk.com/public/style_images/master/comment_add.png" />
  210. @*<asp:linkbutton id="lnkpostReply" runat="server" onclick="lnkpostReply_Click" text="Reply"></asp:linkbutton>*@
  211. @if (Session["UserName"] == null)
  212. {
  213. @Html.ActionLink("Add Reply", "PostReply", "Home", new { title = "Please login to post replys", @class = "disabled", onclick = "javascript:return false;", TechID = item.QuestionID })
  214. }
  215. else
  216. {
  217. @Html.ActionLink("Add Reply", "PostReply", "Home", new { @class = "active", onclick = "javascript:return true;", QuestionID = item.QuestionID, TechID = item.TechID }, null)
  218. }
  219. </li>
  220. </ul>
  221. }
  222. </div>
  223. </div>
  224. </div>
  225. }
  226. }
  227. </div>
The result is as follows:
replies.jpg

That's it; the forums application is over.
Download the code and test it by creating the database with the given tables by adding the entity model to the application.

Check out my sample video for the demo, no audio in that just to show an overview of how the application runs.

If any queries please feel free to ask.