Click here to Skip to main content
13,350,029 members (50,140 online)
Click here to Skip to main content
Add your own
alternative version

Stats

21.3K views
44 bookmarked
Posted 28 Sep 2014

Big n Bulky "How To" Document for ASP.NET MVC, Entity Framework, LINQ, HTML 5 and JQuery

, 28 Sep 2014
Rate this:
Please Sign up or sign in to vote.
This is terribly unorganized document with mix of MVC, Entity Framework, LINQ, HTML 5 and JQuery how tos...

Introduction

This article is collection of "How Tos" that I came across while building my first ASP.NET MVC application. This article can be useful for developers who are migrating from web forms to MVC and planning to develop their first ASP.NET MVC application. (It may not be that useful for beginners).

I admit that I goggled extensively and collected information from various resources but most important are:

  1. http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4
  2. http://www.apress.com/9781430242369
  3. http://stackoverflow.com/
  4. http://www.codeproject.com/

How Tos?

  1. How to clear textbox value using jquery?

    $("#CandidateName").val('');
    
  2. How to reset dropdown list using jquery

    $('#TestBatchId option:eq(0)').attr('selected', 'selected');
    
  3. How to apply css style to helper method in MVC

    @Html.TextAreaFor(model => model.Que, new { @class = "form-control" })
    
  4. How to generate auto password

    String Password = System.Web.Security.Membership.GeneratePassword(6,0)
    
  5. How to submit form using javascript

    document.forms[0].submit();
    
  6. How to fix position of div (in bottom right corner)?

    <div style="position: fixed; right: 0; bottom:0">
    </div>
    
  7. How to access viewbag value in javascript

    var testDuration = '@ViewBag.TestDuration';
    
  8. How to declare variable inside html table using razor.

    @{int srNo = 1; }
    
  9. How to display decimal value on view? Or

  10. Hot to specify floating point number to display in javascript?

    item.Percentage.toFixed(2)
    
  11. How to Create authentication cookie

    FormsAuthentication.SetAuthCookie(logon.UserName, false);
    
  12. How to make sure that at least one checkbox is checked using JQuery?

    <script>
        $("#btnSubmit").click(function (e) {
            if ($("#gender:checked").length === 0) {
                e.preventDefault();
                alert("select gender");
                return false;
            }
        });
    </script>
    
  13. How to call function on selecting checkbox

    $("input[type='checkbox']").change(function () {
        alert("Hello");
    });
    
  14. How to check if dropdownlist item is selected or not?

    if($("#RoomId").val() === "")
    {
        alert("Room Not Selected!");
        return;
    }
    
  15. How to get selected value of dropdownlist using jquery

    var id = parseInt($("#RoomId").val());
    
  16. How to get selected text of dropdownlist using jquery

    var roomName = $("#RoomId option:selected").text()
    
  17. How to generate non repeating random numbers

    List<int> nos = new List<int>();
    Random r = new Random();
    do
    {
        int no = r.Next(1, 11);
        if (!nos.Contains(no))
            nos.Add(no);
    } while (nos.Count != 10);
    
  18. How to call javascipt function once view is loaded / on form load event

    $(document).ready( function () {
        fun1 ();
    }
    
  19. How to align div in center vertically and horizontally?

    div
    {
        width: 100px;
        height: 100px;
        background-color: red;
    
        position: absolute;
        top:0;
        bottom: 0;
        left: 0;
        right: 0;
    
        margin: auto;
    }
    
  20. How to display only date and ignore time while working with dates in MVC

    Model:
    [DataType(DataType.Date)]
    public Nullable<System.DateTime> JoiningDate { get; set; }
    
    Razor / View
    @Html.TextBoxFor(model => model.JoiningDate, "{0:dd/MM/yyyy}"})
    
  21. How to get parent of element using jquery? Or

  22. How to get second or higher level of parent of element using jquery?

    $(this).parents(':eq(6)').css({ "border": "2px solid red" });
    
  23. How to declare variable in view using razor

    @{int srNo = 1; }
  24. How to Use special character like html tag in razor in MVC?

    Html can be included in razor using @: for example:

    @:<td>
  25. How to pass select list to dropdown list from controller to view? Or

  26. How to use dropdown list in MVC?

    Requirement: While creating TestBatch for Specific Test all available tests should get populated in dropdown list, so that one can be selected from. Solution: There are more than one ways to do it. I have used following technique.

    1. First create view model (View Model is class specifically created to pass data from controller to view. You should create separate folder ‘ViewModel’ to keep all your view models at one place.)
      public class SelectTestViewModel
      {
          public int TestId { get; set; }
          public string TestName { get; set; }
          public bool IsSelected { get; set; }
      }
      
    2. Create List of SelectTestViewModel and populate it with all tests from database.
    3. Create object of SelectList class passing list created in above step . Save this object to viewbag using key TestId. We are intentionally using TestId as a key. We will be using same name for dropdown list in view to take advantage of MVC conventions and binding.
    4. SelectList is specialised class to be used with dropdown lists or any list control. It resides in System.Web.Mvc namespace
    5. First parameter is list of Tests, second is Value field, Third is Text field and last is pre-selected item in this case it is null
          public ActionResult Create()
          {
              PopulateTestData();
              return View();
          }
          private void PopulateTestData()
          {
              //If using unit of work and repository pattern
              var allTests = unitOfWork.TestRepository.Get();
              //if not using unit of work and repository pattern
              //OnlineTestDBContext db = new OnlineTestDBContext();
              //var allTests = db.Tests;
              var allTestsViewModel = new List<selecttestviewmodel>();
              foreach (var test in allTests)
              {
                  allTestsViewModel.Add(new SelectTestViewModel
                  {
                      TestId = test.TestId,
                      TestName = test.TestName,
                      IsSelected = false
                  });
              }
              ViewBag.TestId = new SelectList(allTestsViewModel, "TestId", "TestName", null);
          }
      </selecttestviewmodel>
      
    6. In view use helper method. Fist parameter is Name of control which is same as key in ViewBag so automatically will get bonded to SelectList object. Second parameter is just text to display on dropdown list by default.
    7. After submitting form selected TestId will get submitted and will automatically bind to TestId property of model entity.
      @Html.DropDownList("TestId","--Select Test--")
  27. How to have star rating input or display?

    Use rateit plugin

    Refer: http://rateit.codeplex.com/
    
  28. How to create calander ui for appointment or booking type of application?

    Use FullCalendar and Moment plugins

    http://momentjs.com/
    http://fullcalendar.io/
    
  29. How to use checkboxes in MVC

    Requrement: Question can be applicable in multiple tests. So while uploading question I should get chance to select multiple tests for the question. Also note that there is many-to-many relationship between ‘Test’ and ‘Question’; Junction table TestQuestion manages this relationship. It has only two columns TestId and QuestionId. For detail refer to question “How to manage many-to-many relationship in entity framework”
    Solution: All available tests should be populated in checkbox so that user can able to select multiple tests for question

    1. Question Entity
      public class Question
      {
          public Question()
          {
              //Some other stuff
              this.Tests = new HashSet<Test>();
          }
      
          public int QuestionId { get; set; }
          //Some other stuff
      
          public virtual ICollection<Test> Tests { get; set; }
      }
      
    2. Test Entity
      public class Test
      {
          public Test()
          {
              //Some other stuff
              this.Questions = new HashSet<Question>();
          }
      
          public int TestId { get; set; }
          [Required]
          public string TestName { get; set; }
      
          //some other stuff
      
          public virtual ICollection<Question> Questions { get; set; }
          //some other stuff
      }
      
    3. Specify many-to-may relationship in datacontext
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
           modelBuilder.Entity<Test>()
          .HasMany(t => t.Questions)
          .WithMany(t => t.Tests)
          .Map(m =>
          {
              m.ToTable("TestQuestion");
              m.MapLeftKey("TestId");
              m.MapRightKey("QuestionId");
          });
          modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
      }
      
    4. Create SelectTestViewModel
      public class SelectTestViewModel
      {
          public int TestId { get; set; }
          public string TestName { get; set; }
          public bool IsSelected { get; set; }
      }
      
    5. Write PopulateAvailaleTestData() method: While writing this method we are writing it keeping in mind requirement of edit mode also; where we need to show applicable tests for questions as selected. So this method accepts Question as parameter and fetches currently selected tests. This parameter is not useful for create operation as there are no selected tests and returns null.
      //question parameter is usefull while editing existing question
      private void PopulateAvailableTestData(Question question)   //question parameter is usefull while editing existing question
      {
          var allTests = unitOfWork.TestRepository.Get();
      
          //retrives current applicable tests. useful for edit opetaion. null while creating new question
          var assignedTests = new HashSet<int>(question.Tests.Select(t => t.TestId));
          var allTestsViewModel = new List<SelectTestViewModel>();
          foreach (var test in allTests)
          {
              allTestsViewModel.Add(new SelectTestViewModel
              {
                  TestId = test.TestId,
                  TestName = test.TestName,
                  //for new question all options sets to flase while editing existing questions current applicable tests gets selected
                  IsSelected = assignedTests.Contains(test.TestId)
              });
          }
          ViewBag.Tests = allTestsViewModel;
      }
      
    6. Write Get Action Method for Create()
      public ActionResult Create()
      {
          var question = new Question();
          question.Tests = new List<Test>();
          PopulateAvailableTestData(question);
          return View();
      }
      
    7. Write Post Action Method for Create(): Note that parameter ‘selectedTests’ is same as of name of checkboxes in view. So that checkbox selected values i.e TestIds will get submitted to selectedTests array.
      [HttpPost]
      public ActionResult Create(Question question, string[] selectedTests)
      {
          if(selectedTests != null)
          {
              question.Tests = new List<Test>();
              foreach(var test in selectedTests)
              {
                  var testToAdd = unitOfWork.TestRepository.GetByID(int.Parse(test));
                  question.Tests.Add(testToAdd);
              }
          }
      
          if(ModelState.IsValid)
          {
              unitOfWork.QuestionRepository.Insert(question);
              unitOfWork.Save();
              return RedirectToAction("Index");
          }
          return View();
      }
      
    8. View to create question: foreach loop will display checkboxes for all available tests. If condition to display checkboxes in three columns only. For create operation line @(Html.Raw(test.IsSelected ? "checked=\"checked\"" : "")) can be removed it is required for edit operation. It selects checkbox for currently applicable tests.
          <table>
          <tr>
          @{
              int cnt = 0;
              List<OnlineTest.ViewModel.SelectTestViewModel> tests = ViewBag.Tests;
      
              foreach (var test in tests)
              {
                  if (cnt++ % 3 == 0)
                  {
                          @:</tr><tr>
                  }
                  @:<td>
                  <input class="" type="checkbox"
                          name="selectedTests"
                          id="selectedTests"
                          value="@test.TestId"
                  @(Html.Raw(test.IsSelected ? "checked=\"checked\"" : "")) />
                  @: @test.TestName    
                  @:</td>
              }
              @:</tr>
          }
          </table>
      <span style="display: none;"> </span>
      
  30. How to use multiple groups of checkboxes in MVC? Or

  31. How to submit multiple groups of checkboxes? Or

  32. How to populate random questions for different users? Or

  33. How to generate random numbers with in specific range? Or

  34. How to use Dictionary?

    I wanted to render one page question paper i.e. if there are 25 questions all should come one below other with their options and question can have multiple answers so options to be displayed using checkboxes. Now problem was how to generate group of this options and how to identify which set of options selected for which question

    1. Create OptionsViewModel
      public class OptionsViewModel
      {
          public int OptionId { get; set; }
          public string Option { get; set; }
          public bool IsSelected { get; set; }
      }
      
    2. Create QuestionWithOptionsViewModel
      public class QuestionWithOptionViewModel
      {
          public int QuestionId { get; set; }
          public string Question { get; set; }
          public List<OptionsViewModel> Options { get; set; }
      
          public QuestionWithOptionViewModel()
          {
              Options = new List<OptionsViewModel>();
          }
      }
      
    3. Get QuestionPaper()
      public ActionResult QuestionPaper()
      {
          //Applicable TestId for logged in user saved in session when user logs in.
          int testId = (int)Session["TestId"];
          Test Test = unitOfWork.TestRepository.Get(t => t.TestId == testId).FirstOrDefault();
          var questions = Test.Questions;
          List<QuestionWithOptionViewModel> questionsWithOptions = new List<QuestionWithOptionViewModel>();
          QuestionWithOptionViewModel queWithOpt;
      
          //Answers Dictonary holds the right answers. QuestionId as key and comma seprated OptionIds as value. (OptionIds of correct options only)
          //Answer Dictonary will be later used to calculate results
          Dictionary<int, string> Answers = new Dictionary<int, string>();
      
          //Code to gererate Non-repeating array of random numbers. List 'nos' is used to populate random questions.
          List<int> nos = new List<int>();
          Random r = new Random();
          do
          {
              int no = r.Next(0, Test.Questions.Count);
              if (!nos.Contains(no))
                  nos.Add(no);
          } while (nos.Count != Test.TotalQuestions);
      
      
          foreach(int no in nos)
          {
              Question question = Test.Questions.ElementAt(no);
              string ansStr = "";
              queWithOpt = new QuestionWithOptionViewModel();
              queWithOpt.QuestionId = question.QuestionId;
              queWithOpt.Question = question.Que;
              foreach (var optionItem in question.Options)
              {
                  queWithOpt.Options.Add(new OptionsViewModel{
                      OptionId = optionItem.OptionId,
                      Option = optionItem.AnsOption,
                      IsSelected = false,
                  });
                  if(optionItem.IsAnswer == true)
                  {
                      if (ansStr.Length == 0)
                          ansStr = optionItem.OptionId.ToString();
                      else
                          ansStr += "," + optionItem.OptionId;
                  }
              }
              questionsWithOptions.Add(queWithOpt);
              Answers.Add(question.QuestionId, ansStr);
          }
      
          TempData["Answers"] = Answers;
      
          //some other stuff
          return View(questionsWithOptions);
      }
      
    4. Must know about check boxes:
      1. Browser doesn’t submit anything for unselected checkbox. Neither null nor false.
      2. Brower submits comma separated values for selected checkboxes with same name.
      3. On server side values can be accepted in FormCollection object. Checkboxes Name property used as key for set of selected checkboxes.
        1. Values can be accessed as Collection[i]
        2. Key can be access as Collection.Keys[i]
    5. Post QuestionPaper(): When user submits question paper all the selected option will be submitted to collection object.
          [HttpPost]
          public ActionResult QuestionPaper(FormCollection collection)
          {
              Dictionary<int, string=""> Answers = (Dictionary<int, string="">)TempData["Answers"];
              int marks = 0;
              for (int i = 1; i < collection.Keys.Count; i++ )
              {
                  string rightAnswer = Answers[int.Parse(collection.Keys[i])];
                  string userAnswer = collection[i];
                  if(userAnswer == rightAnswer)
                  {
                      marks++;
                  }
              }
              //some other stuff
          }
      </int,></int,>
      
    6. View: Note that options use OptionId as value and QuestionId as Name. That means if a Question have 4 options then all options will have same name.
      <div id="@srNo" class="panel-collapse collapse in">
          <div class="panel-body">
              <table class="table">
                  @{int opNo = 0;}
                  @foreach (var option in item.Options)
                  {
                      <tr>
                          <td>
                              <input class="ansoption" type="checkbox" name="@item.QuestionId" value="@option.OptionId" />
                              @option.Option
                          </td>
                      </tr>
                      opNo++;
                  }
              </table>
          </div>
      </div>
      
  35. How to do AJAX call from dropdownlist? Or

  36. Hot to display data in table / grid format? Or

  37. How to serialize data as JSON?

    Requirement:Dropdown list populated with all batches. Selecting batch should submit batch id asynchronously to action.
    1. ScoreJSonModel:Data will be stored in object of this class and then will serialize to JSON
      public class ScoreJsonModel
      {
          public string TestName { get; set; }
          public string TestDate { get; set; }
          public int TotalQuestions { get; set; }
          public int TotalMarks { get; set; }
          public string Duration { get; set; }
          public int TestTakerId { get; set; }
          public string UserId { get; set; }
          public string Name { get; set; }
          public int ScoredMarks { get; set; }
          public double Percentage { get; set; }
      }
      
    2. ScoreController:
      public class ScoreController : Controller
      {
          UnitOfWork unitOfWork = new UnitOfWork();
      
          public ActionResult Index(int? TestBatchId = null)
          {
              if(TempData["TestBatchId"] != null)
                  TestBatchId = (int)TempData["TestBatchId"];
              PopulateBatches(TestBatchId);
              return View();
          }
      
          public JsonResult BatchwiseScore(int? TestBatchId = null)
          {
              //if (TempData["TestBatchId"] != null && TestBatchId == null)
              //    TestBatchId = (int)TempData["TestBatchId"];
      
              if (TestBatchId != null)
              {
                  TempData["TestBatchId"] = TestBatchId;
              }
              PopulateBatches(TestBatchId);
              var scores = unitOfWork.ScoreRepository.Get(tb=>tb.TestTaker.TestBatchId == TestBatchId,s => s.OrderByDescending(m=>m.TestScore));
              List<ScoreJsonModel> scoresJsonModelList = new List<ScoreJsonModel>();
              foreach (var s in scores)
              {
                  ScoreJsonModel scoreJsonModel = new ScoreJsonModel
                      {
                          TestName = s.TestTaker.TestBatch.Test.TestName,
                          TestDate = s.TestTaker.TestBatch.Test.Date.ToShortDateString(),
                          TotalQuestions = s.TestTaker.TestBatch.Test.TotalQuestions,
                          TotalMarks = s.TestTaker.TestBatch.Test.TotalMarks,
                          Duration = s.TestTaker.TestBatch.Test.Duration.ToString(),
                          TestTakerId = s.TestTakerId,
                          UserId = s.TestTaker.LoginId,
                          Name = s.TestTaker.TestTakerInfo.FirstName + " " + s.TestTaker.TestTakerInfo.LastName,
                          ScoredMarks = s.TestScore,
                          Percentage = (float)s.TestScore / (float)s.TestTaker.TestBatch.Test.TotalMarks * 100.0
                      };
                  scoresJsonModelList.Add(scoreJsonModel);
              }
              return Json(scoresJsonModelList, JsonRequestBehavior.AllowGet);
          }
      
      
          private void PopulateBatches(object selectedBatch = null)
          {
              var batches = from batch in unitOfWork.TestBatchRepository.Get() select new { batch.TestBatchId, batch.TestBatchName };
              ViewBag.TestBatchId = new SelectList(batches, "TestBatchId", "TestBatchName", selectedBatch);
          }
      }
      
  38. How to save json data using jquery ajax in MVC?

    MVC is smart enough to parse json data to your model object. No extra step need to be done. (At least for me it worked) Only take care while creating json object in javascript function; json keys should match with model properties. Refer following sample code.
    Model:
    public partial class Booking
    {
        public int BookingID { get; set; }
        public int RoomID { get; set; }
        public string BookedBy { get; set; }
        public string MeetingTitle { get; set; }
        public System.DateTime BookingDate { get; set; }
        public System.DateTime FromTime { get; set; }
        public System.DateTime ToTime { get; set; }
    
        public virtual Room Room { get; set; }
    }
    
    Script in view
    $('#btnSaveMeeting').click(function () {
    $('#popupForm').hide();
    
    var dataRow = {
        'BookedBy': bookedBy,
        'RoomID': $("#RoomId").val(),
        'BookingDate': localStorage["bookingDate"],
        'FromTime': localStorage["startTime"],
        'ToTime': localStorage["endTime"],
        'MeetingTitle': $("#MeetingTitle").val()
    }
    
    $.ajax({
        type: 'POST',
        url: '@Url.Action("SaveMeeting", "Room")',
        data: dataRow,
        success: function (response) {
            if (response == 'True') {
                //$('#calendar').fullCalendar('refetchEvents');
                alert('Meeting Saved!');
            }
            else {
                alert('Error, could not save meeting!');
            }
        }
    });
    
    Controller
    public bool SaveMeeting(Booking BookingDetails)
    {
        BookingDetails.BookedBy = Session["EmpID"].ToString();
        resdemoEntities dc = new resdemoEntities();
        dc.Bookings.Add(BookingDetails);
        dc.SaveChanges();
        return true;
    }
    
  39. How to use datetimepicker to enter dates?

  40. How to change format of datetimepicker to yy-mm-dd?

    Make sure that you have referred following three jquery files:

    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script src="~/Scripts/jquery-ui-1.10.4.min.js"></script>
    <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
    
    Html:
    <input type="text" id="TestDate" name="TestDate" />
    
    Script: Type in bottom of view
    <script language="javascript">
        $("#TestDate").datepicker({ dateFormat: "yy-mm-dd" });
    </script>
    
  41. How to put validation for Duration textbox to check pattern in hh:mm:ss format?

  42. How to provide masked text box to enter duration or date like formats in MVC?

  43. How to use Jquery Masked plugin?

    1. Install Jquery Masked plugin using package manager
    2. Refer it in view
      <script src="~/Scripts/jquery.maskedinput-1.3.1.min.js"></script>
      
    3. HTML/Body:
      @Html.EditorFor(model => model.Duration) or
      <input type="text" id="Duration" name="Duration" />
      
    4. Script: Add to buttom of view
      <script>
          $("#Duration").mask("99:99:99");
      </script>
      
    5. check http://igorescobar.github.io/jQuery-Mask-Plugin/
      
  44. how to create thumbnail list in MVC using bootstrap?

    <div class="row">
        @foreach (var item in Model)
        {
            <div class="col-sm-2">
                <a href="#" class="thumbnail">
                    <img src="@item.ImageUrl" alt="@item.EmpID" />
                </a>
                <div class="caption text-center">
                    <h5>@item.EmpName</h5>
                </div>
            </div>
        }
    </div>
    
  45. How to persist filter value between page redirects?

    I filtered data on page1 then visited page2 now when I come back to page1 it should show filtered list. One of the soultion is using TempData. TempData object resides in server memory only till we access it once. So it is memory efficient.

    public ActionResult Index(int? testId = null)
    {
        if (TempData["TestId"] != null)
            testId = (int)TempData["TestId"];
    
        if (testId != null)
        {
            TempData["TestId"] = testId;
        }
    
        PopulateTestDropDown(testId);
        Question[] questions  = unitOfWork.QuestionRepository.Get(q => q.Tests.Any(t=>t.TestId == testId)).ToArray();
    
        return View(questions);
    }
    
  46. where to save values from javascript for future use?

  47. How to use session storate / localstorage / webstorage in HTML5

    sessionStorage["bookingDate"] = moment(start).format();
    sessionStorage["startTime"] = moment(start).format("hh:mm a");
    sessionStorage["endTime"] = moment(end).format("hh:mm a");
    var dateTimeDetails = moment(sessionStorage["bookingDate"]).format("ddd MMM D") + " " + sessionStorage["startTime"] + " - " + sessionStorage["endTime"];
    $('#BookingDateTime').text(dateTimeDetails);
    Refer: http://www.w3schools.com/html/html5_webstorage.asp
    
  48. How to compare only dates in linq query?

    use System.Data.Entity.DbFunctions.TruncateTime();
    var result = (from meeting in dc.Bookings
              where DbFunctions.TruncateTime(meeting.BookingDate) >= DbFunctions.TruncateTime(fromDate) && DbFunctions.TruncateTime(meeting.BookingDate) <= DbFunctions.TruncateTime(toDate)
             select meeting).ToList();
    
  49. How to write left outer join query in linq?

    To write left outer join you need to use two keywords:
    1. into
    2. DetaultIfEmpty
    var result = from emp in dc.EmployeeDetails
    join review in dc.ReviewManager on emp.EmpID equals review.EmpID into t
    from rt in t.DefaultIfEmpty()
    select new TeamMemberViewModel {EmpName = emp.EmpName, ManagerRating = rt.Rating != null ? rt.Rating : 0 };
    
  50. How to enable Code first migration? Or

  51. How to update database schema without deleting data while using code first approach? Or

  52. How to enable Code first migration when context class is in class library project? Or

  53. How to update database after changing entity classes?

    Updating database for entity changes is three step process. We have to use following three commands Enable-Migrations: Enables database for code-first migration. This step is one time step. Once database is enabled next time only execute second and third step. Add-Migration: Creates script file with all the changes in entity classes Update-Database: Executes script created using Add-Migration command (in previous step) on database to actually upsize database. In my case I had two projects.

    1. OnlineTest: ASP.NET MVC Web application
    2. OnlineTestDomain: Domain model for OnlineTest. With DAL and Entity classes and DbContext class. As DbContext class is in separate class library we have to specify it while executing all above commands.

    Following are the commands that I used

    //required only once
    Enable-Migrations –ProjectName OnlineTestDomain -StartUpProjectName OnlineTest -Verbose
    
    //Here Migration1 is key it should change every time. For example next time it can be Migration2
    Add-Migration -ProjectName OnlineTestDomain -StartUpProjectName OnlineTest -Verbose Migration1
    
    Update-Database -ProjectName OnlineTestDomain -StartUpProjectName OnlineTest -Verbose
    
  54. How to create one-to-one relationship in entity framework code first ? Or

  55. How to disabled auto increment in code first?

    Requirement: There are two tables TestTaker and TestTakerInfo having one-to-one relationship

    1. TestTaker: Holds automatically created Login Ids and Passwords and TestTakerId
    2. TestTakerInfo: To save information about TestTaker like Name, Contact no etc. This information will be filled by test taker after logging in to system
    3. Table structure is as follow
    4. Important:
    5. TestTakerInfo Table doesn’t have auto-incremented TestTakerInfoId column
    6. TestTakerId is working as primary key as well as foreign key in TestTakerInfo Table
    7. TestTakerID in TestTakerInfo should not be auto generated.
    TestTaker
    TestTakerId LoginId
    1 user-1
    2 user-2
    TestTakerInfo
    TestTakerId Name
    1 Name1
    2 Name2
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<testtakerinfo>().HasKey(t => t.TestTakerId);
    
        modelBuilder.Entity<testtakerinfo>().Property(t => t.TestTakerId)
                    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
    
        modelBuilder.Entity<testtakerinfo>()
                    .HasRequired(t => t.TestTaker)
                    .WithOptional(t => t.TestTakerInfo);
    }
    
  56. How to Specify Junction table for many-to-many relationships in code first? Or

  57. How to create many-to-many relationship using entity framework code first?

    Requirement: A Test is a set of multiple questions at the same time Question can be applicable for multiple Tests.
    solution
    • This problem can be solved by establishing many-to-many relationship between Test and Question Table.
    • To create many-to-many relationship between two tables we have to introduce junction table.
    • In following example TestQuestion table holds many-to-many relationship between Test and Question tables.
    • Test 1 has questions 1, 2 and 3
    • Test 2 has questions 3 and 4
    • Question 3 is applicable in Test 1 and Test2
    Test
    TestId TestName
    1 Test1
    2 Test2
    3 Test3
    TestQuestion
    TestId QuestionId
    1 1
    1 2
    1 3
    2 3
    2 4
    Question
    QuestionId Que
    1 Question1
    2 Question2
    3 Question3
    4 Question4

    This relationship can be created in entity framework code first using fluent API in DBContext class

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         modelBuilder.Entity<test>()
        .HasMany(t => t.Questions)
        .WithMany(t => t.Tests)
        .Map(m =>
        {
            m.ToTable("TestQuestion");
            m.MapLeftKey("TestId");
            m.MapRightKey("QuestionId");
        });
         modelBuilder.Conventions.Remove<manytomanycascadedeleteconvention>();
    }
    
  58. How to fetch from tables having Many to Many relationship (junction table)

    var questions = unitOfWork.QuestionRepository.Get(q => q.Tests.Any(t => t.TestId == testId));
    
  59. How to delete record having many-to-many relationship in Entity Framework?

    If deleting record having manay to many relationship is troubling you. try out follwing in OnModelCreating method of DBContext class
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    
  60. How to add permissions to database so that website should work after deployment on IIS

  61. How to resolve error “Login Failed to db, CREATE TABLE permission denied in database”?

    Once website is deployed on IIS all request tries to access database using [IIS APPPOOL\ASP.NET v4.0] account. (This can be different in your case depending on version you using). So we need to add this account to database.

    1. Open SQL Server Management Studio
    2. Go to Security -- Logins
    3. Right click on Logins -- New Login -- Search for IIS APPPOOL\ASP.NET v4.0 -- Add
    4. Expand database -- go to Security -- Users
    5. Right click on Users -- New User -- Type ‘IISUser’ in user name. (can be anything) -- Search for login name ‘IIS APPPOOL\ASP.NET v4.0’ -- Specify default schema as ‘db_owner’
  62. How to resolve if AJAX call not working after deploying on IIS?

    Harcoded link path may not work properly after deploying application on IIS. Instead of using hardcoded path use URL helper method as below

    url: '@Url.Action("FunctionName", "Controller")'
    
  63. How to resolve session expire / timeout problem?

    If there is no interaction with server for long time then it can cause following 2 issues
    1. Session object gets expired on server
    2. Authentication cookie file gets expired at client side
    Session expire issue need to be handled at three levels as follow:
    1. Change session timeout in web.config file. (By default it is 20 mins)
      <system.web>
              <sessionState timeout="300" />
      </system.web>
      
    2. Open IIS using inetmgr command -- select your website in left pane -- in feature view -- double click ‘session state’ -- in Cookie Settings section Type 300 in Time-out Textbox
    3. Select Application Pools -- right click on ASP.NET v4.0 (or as per your version) -- Advance Settings -- Set Idle Time-out as 300
    Handling Cookie Expiration issue: In web.config file specify timeout in forms tag
    <system.web>
        <sessionState timeout="300" />
        <authentication>
            <forms loginUrl="Account/Logon" timeout="300"/>
        </authentication>
        </system.web>
    
  64. how to convert HttpPostedFileBase to image?

    Image img = Image.FromStream(HttpPostedFileBase.InputStream);
    
  65. How to resolve "Maximum request length exceeded" error while uploading images?

    Insert following sections in web.config file

    <system.web>
        <httpRuntime  maxRequestLength="1048576" executionTimeout="3600" />
    </system.web>
    
    and
    <system.webServer>
      <security>
        <requestFiltering>
          <requestLimits maxAllowedContentLength="1073741824" />
        </requestFiltering>
      </security>
    </system.webServer>
    
  66. How to use viewBag in javascript?

    var selectedEventId = '@ViewBag.SelectedEventId';  //Notice single quotes
    
  67. How to display helpful error messages instead of generic message?

    <system.web>
        <customErrors mode="Off" />
      ...
    </system.web>
    
  68. How to resolve if not working in IE 11?

    In web.config file just above </configuration> put following configuration
    <system.webServer>
        <httpProtocol>
          <customHeaders>
            <clear />
            <add name="X-UA-Compatible" value="IE=10" />
          </customHeaders>
        </httpProtocol>
    </system.webServer>
    

Some Useful Libraries and Plugins:

  1. http://getbootstrap.com/
  2. http://jquery.com/
  3. http://jqueryui.com/
  4. http://momentjs.com/
  5. http://fullcalendar.io/
  6. http://countdownjs.org/
  7. http://plugins.jquery.com/maskedinput/
  8. http://rateit.codeplex.com/

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

13+ Years of Experience. Seen death and rise of various technologies. Started with VB - 6.0 back in 2004, then updated to .NET somewhere in 2008. used Win Forms, ASP.NET Web Forms. Switched to ASP.NET MVC in 2013 for very short time. Right now using ASP Core since 2015 when it was in RC 1.

You may also be interested in...

Comments and Discussions

 
QuestionMy vote of 5 Pin
ashish68919-Aug-15 3:18
professionalashish68919-Aug-15 3:18 
GeneralMy Vote 5 Pin
Shemeemsha RA2-Oct-14 6:46
memberShemeemsha RA2-Oct-14 6:46 
QuestionThanks for sharing! Pin
iSahilSharma30-Sep-14 9:31
professionaliSahilSharma30-Sep-14 9:31 
QuestionMVC controller (insert ,update ,delete, ) Pin
manoj s sherje30-Sep-14 0:42
membermanoj s sherje30-Sep-14 0:42 
AnswerRe: MVC controller (insert ,update ,delete, ) Pin
Bhushan Mulmule1-Oct-14 22:42
professionalBhushan Mulmule1-Oct-14 22:42 
Questiongreat Pin
Sacha Barber28-Sep-14 21:46
mvpSacha Barber28-Sep-14 21:46 
AnswerRe: great Pin
Bhushan Mulmule1-Oct-14 22:44
professionalBhushan Mulmule1-Oct-14 22:44 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun28-Sep-14 20:21
memberHumayun Kabir Mamun28-Sep-14 20:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 28 Sep 2014
Article Copyright 2014 by Bhushan Mulmule
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid